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, and only nodes itself is 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
Using the stack, each k nodes into the stack, and then out of the stack, the implementation of the reverse order.
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode*reversekgroup (ListNode *head,intk) {ListNode* Newhead =NewListNode (-1); ListNode* Tail =Newhead; ListNode* begin =Head; ListNode* end =begin; while(true) { intCount =K; while(Count && End! =NULL) {End= end->Next; Count--; } if(Count = =0) {//reverse from [begin, end]Stack<listnode*>s; while(Begin! =end) {S.push (begin); Begin= begin->Next; } while(!S.empty ()) {ListNode* top =S.top (); S.pop (); Tail->next =top; Tail= tail->Next; } } Else {//Leave outTail->next =begin; Break; } } returnNewhead->Next; }};
"Leetcode" Reverse Nodes in K-group