Leetcode Reverse Nodes in k-Group


Reverse Nodes in k-Group  
Total Accepted: 3777 
Total Submissions: 16058 My Submissions
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;
    }
};