Given A linked list, reverse the nodes of a linked list K at a time and return its modified list.
K is a positive integer and was less than or equal to the length of the linked list. If the number of nodes is not a multiple of K then left-out nodes in the end should remain as it is.
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
Note:
- Only constant extra memory is allowed.
- You could not alter the values in the list ' s nodes, and only nodes itself could be changed.
Code
Using a stack
/** * Definition for singly-linked list. * struct ListNode {* int val; * List Node *next; * ListNode (int x): Val (x), Next (NULL) {}}; */class Solution {public:listnode* Reversekgroup (listnode* head, int k) {stack<listnode*> s; listnode* dummy = new ListNode (0); Dummy->next = head; listnode* current = dummy; listnode* next = dummy->next; while (next) {for (int i = 0; i < k && next = NULL; ++i) {s.push (next); Next = next->next; } if (S.size ()! = k) return dummy->next; while (!s.empty ()) {current->next = S.top (); S.pop (); Current = current->next; } Current->next = Next; } return dummy->next; }};
Runtime: MS, faster than 32.59% of C + + online submissions for Reverse Nodes in K-group.
This isn ' t conform with this question ' s demand.
The right-is:
Class Solution {public: listnode *reversekgroup (listnode *head, int k) { if (head==null| | K==1) return head; int num=0; ListNode *preheader = new ListNode ( -1); Preheader->next = head; ListNode *cur = Preheader, *nex, *pre = Preheader; while (cur = cur->next) num++; while (num>=k) { cur = pre->next; NEX = cur->next; for (int i=1;i<k;++i) { cur->next=nex->next; nex->next=pre->next; pre->next=nex; nex=cur->next; } Pre = cur; num-=k; } Return preheader->next; }};
Runtime: MS, faster than 16.72% of C + + online submissions for Reverse Nodes in K-group.
It'll has a difficulty to understand.
Reverse Nodes in K-group