您的位置:首页 > 其它

链表分段翻转

2015-10-11 15:43 411 查看
问题:

 将一个单链表每K个一组进行翻转
1->2->3->4->5

假如
k=2,则变成2->1->4->3->5
k=3,则变成3->2->1->4->5

接口函数:ListNode*res(ListNode*head,intk)

代码:









#include<iostream>

using namespace std;

struct ListNode{
int val;
ListNode* next;
ListNode(int v = 0, ListNode* n = NULL) :val(v), next(n){}

};

ListNode* res(ListNode* head,int k){
ListNode* cur_head = head;
ListNode* next_head = head;
ListNode* new_head = head;
//找出新的头节点
int t = k-1;
while (next_head && t--){
next_head = next_head->next;
}
//处理第一段
ListNode* pre_node=NULL;
if (t == -1 && next_head){
new_head = next_head;
//第2,3,4...段
cur_head = new_head->next;
next_head = new_head->next;
//翻转
t = k;
ListNode* cur_node = head;
ListNode* new_next_node = next_head;
//这个很重要,用来连接下一段的
pre_node = cur_node;
while (t--){
ListNode* next_node = cur_node->next;
cur_node->next = new_next_node;
new_next_node = cur_node;
cur_node = next_node;
}
}
else{
return new_head;
}

while (next_head){
t = k;
cur_head = next_head;
//找出剩余链表是否还足够k个
while (next_head && t--){
next_head = next_head->next;
}
//结束
if (t>-1){
break;
}
else{
t = k;
ListNode* cur_node = cur_head;
ListNode* new_next_node = next_head;
while (t--){
ListNode* next_node = cur_node->next;
cur_node->next = new_next_node;
new_next_node = cur_node;
cur_node = next_node;
if (t == 1){
//这个很重要,将上一段的结尾连接到这一段的开头
pre_node->next = cur_node;
}
}
pre_node = cur_head;
}

}
return new_head;

}

int main(){
ListNode* p7 = new ListNode(7);
ListNode* p6 = new ListNode(6,p7);
ListNode* p5 = new ListNode(5, p6);
ListNode* p4 = new ListNode(4, p5);
ListNode* p3 = new ListNode(3, p4);
ListNode* p2 = new ListNode(2, p3);
ListNode* p1 = new ListNode(1, p2);

ListNode* cur = p1;
while (cur){
cout << cur->val << "->";
cur = cur->next;
}
cout << "NULL"<<endl;

ListNode* new_head = res(p1,2);

cur = new_head;
while (cur){
cout << cur->val << "->";
cur = cur->next;
}
cout << "NULL" << endl;

while (1);
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: