Given a linked list, reverse the nodes of a linked list k at a time and return its modified 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
这种题目一般有技巧:
1 增加dummy前置节点,dummy.next指向头节点,可以让程序简洁点
2 注意保存当前节点的next节点
3 可以利用好k来计算,注意准确计算需要操作的节点指针
//2014-1-25 update
class Solution125 {
public:
ListNode *reverseKGroup(ListNode *head, int k)
{
ListNode dummy(0);
dummy.next = head;
ListNode *pre = &dummy;
while (head)
{
int i = 1;
for ( ; i < k && head->next; i++)//容易错误处
{
head = head->next;
}
if (i == k)
{
ListNode *last = pre->next;//容易遗漏处
head = pre->next->next;
for (i = 1; i < k; i++)
{
ListNode *t = head->next;
head->next = pre->next;
pre->next = head;
head = t;
}
pre = last;//容易遗漏处
last->next = head;//容易遗漏处
}
else break;//容易遗漏处
}
return dummy.next;
}
};