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

C++:
01 /**
02  * Definition for singly-linked list.
03  * struct ListNode {
04  *     int val;
05  *     ListNode *next;
06  *     ListNode(int x) : val(x), next(NULL) {}
07  * };
08  */
09 class Solution {
10 public:
11     ListNode *reverseKGroup(ListNode *head, int k) {
12         // Start typing your C/C++ solution below
13         // DO NOT write int main() function
14         if(head==NULL)
15             return NULL;
16         vector<ListNode*> A;
17         stack<ListNode*> B;
18         stack<ListNode*> C;
19         int cnt=0;
20         for(ListNode* p=head;;)
21         {
22             if(cnt==k)
23             {
24                 cnt=0;
25                 while(!B.empty())
26                 {
27                     A.push_back(B.top());
28                     B.pop();
29                 }
30             }
31             else
32             {
33                 if(p==NULL)
34                     break;
35                 cnt++;
36                 B.push(p);
37                 p=p->next;
38             }
39         }
40         while(!B.empty())
41         {
42             C.push(B.top());
43             B.pop();
44         }
45         while(!C.empty())
46         {
47             A.push_back(C.top());
48             C.pop();
49         }
50         ListNode* result=A[0];
51         ListNode* prv=result;
52         for(int i=1;i<A.size();i++)
53         {
54             prv->next=A[i];
55             prv=A[i];
56         }
57         prv->next=NULL;
58         return result;
59     }
60 };
Advertisements
This entry was posted in Array and linked list, Stack and Queue. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s