25.Reverse Nodes in k-Groupはどうやって余分な空間を使って一方向チェーンを反転させないですか?

1716 ワード

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 shound remand 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->5For k = 2,you shoul d return:  2->1->4->3->5For k = 3,you shoul d return:  3->2->1->4->5prehead、cur=headを設定して、Crのnextをpreheadのnextに挿入させます.
一つの法則を発見します.
A->next=B->nextそしてAがBの前にいると 結果としてBはチェーンから外れます.
/**
 * 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(k == 1 || head == NULL) return head;
        ListNode dummy(-1);
        ListNode *prehead = &dummy, *pre = prehead, *cur = prehead, *nex;
        prehead->next = head;
        int n = 0;
        while(cur = cur->next) n++;//   cur    
        while(n >= k){
            cur = pre->next;//   pre    
            nex = cur->next;
            //  cur      k - 1 
            for(int i = 0; i < k - 1; i++){//             int i,          ,                
                cur->next = nex->next;
                nex->next = pre->next;
                pre->next = nex;
                nex = cur->next;
            }
            pre = cur;//cur val              k - 1 ,  k      
            n -= k;
        }
        return prehead->next;
    }
};