[Linked List]Reverse Nodes in k-Group

Total Accepted: 48614 Total Submissions: 185356 Difficulty: Hard

 

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

 
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head)
    {
        ListNode* newHead=NULL,*p=head,*next=NULL;
        while(p){
            next    = p->next;
            p->next = newHead;
            newHead = p;
            p       = next;
        }
        return newHead;
    }
    ListNode* reverseKGroup(ListNode* head, int k) {
        if(k<=1){
            return head;
        }
        ListNode *pre=NULL,*next=NULL;
        ListNode *cur=head;
        ListNode *reverseHead = NULL;
        int cnt = 0;
        while(cur){
            if(cnt==0){
                reverseHead = cur;
            }
            next = cur->next;
            ++cnt;
            if(cnt==k){
                cur->next=NULL;
                ListNode *newHead = reverseList(reverseHead);
                pre ? pre->next = newHead : head=newHead;
                reverseHead->next = next;
                pre = reverseHead;
                cur = next;
                cnt = 0;
            }else{
                cur = cur->next;
            }
        }
        return head;
    }
};
posted @ 2015-12-12 16:01  zengzy  阅读(172)  评论(0编辑  收藏  举报
levels of contents