Description:
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
分析:这道题的意思就是一个链表,从head开始遍历,每经过k个node就将这k个node倒置,如果最后不足k个node,则对余下的node不做任何操作。思路也是很简单,就是链表的倒置,不过由于转置之后必须保持不能断链,我们可以在k个node前后各加一个node,处理倒置时,只对中间k个倒置,操作完成后,整个k+2个node与其他外部node关系没有任何改变,仅仅只是k+2中的内部链做了改变。最后呢,这道题犯了一个严重错误,导致我IDE上编译正确,而submit却一直出错,就是while(p2 != cur)错写成了while(p3 != cur),这个错误非常有意思,它只会在list的长度是k的整数倍的时候出现问题,同时又由于我引用了未初始化的指针p3(p3应该指向乱七八糟的地方了 所以编译通过 但是提交时估计系统帮我置空了 所以又不能通过)。最后po上代码:
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if(!head || !head->next || k == 1)
return head;
ListNode new_head(0);
ListNode *phead;
ListNode *p1, *p2, *p3; //还是没有置NULL 死性难改!!!哈哈哈
ListNode *pre, *cur;
phead = &new_head;
phead->next = head;
pre = cur = head;
int count = 0;
while(cur)
{
cur = cur->next;
count++;
if(count % k == 0)
{
p1 = pre;
p2 = pre->next;
for(int j = 1; j < k; j++)
{
p3 = p2->next;
p2->next = p1;
p1 = p2;
p2 = p3;
}
phead->next = p1;
phead = pre;
pre->next = cur;
pre = cur;
}
}
return new_head.next;
}
};
【你必须非常努力 才能看起来毫不费力】