Wednesday, August 5, 2015

025 - Reverse Nodes in k-Group

Reverse Nodes in k-Group

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
Hide Tags
Linked List
Hide Similar Problems
(M) Swap Nodes in Pairs
 
三个指针,prev, head, end,每 k 个节点 reverse 一次即可。
reverse的时候,依次把头上的元素插入到end的后面,end始终不动。
/**
* 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<2 || NULL == head)
            return head;

        ListNode dummy(0);
        dummy.next = head;
        ListNode* prev=&dummy;
        ListNode* endd=prev;

        while(head)
        {
            int count = k;
            while(count && endd->next)
                endd = endd->next,  count--;


            if(!count)
                prev->next  = reverse(prev, head, endd);
            else
                return dummy.next;


            prev = head, endd = head;
            head = prev->next;
        }
        return dummy.next;
    }
   
    ListNode* reverse(ListNode* prev, ListNode* head, ListNode* endd)
    {
        ListNode* succ = endd->next;
        while(prev->next != endd)
        {
            //move head to end's next
            prev->next = head->next;
            head->next = succ;

            endd->next = head;
           
            //make the moved node as "new next"
            succ = head;

            head = prev->next;
        }
        return prev->next;
    }
};

24 ms.

No comments:

Post a Comment