Reverse Nodes in K-groupTotal Accepted: 57696 Total Submissions: 210241 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, 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
Subscribe to see which companies asked this question
Hide TagsLinked ListHide Similar Problems(E) Swap Nodes in Pairs
Ideas:
/*k=3 first reversal, initial status: -1, 1, 2, 3, 4--5 | | | Pre cur tmp after 1th operation: -1, 2, 1, 3, 4 and 5 | | | PRE cur tmp after 2nd operation: -1, 3-& Gt 2, 1, 4, 5 | | | Pre cur tmp second reversal, initial status: -1, 3, 2, 1, 4--5 | | | Pre cur tmp...*/
Code
/** * 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 (!head | | k<=1) return Head ListNode dummy (0); Dummy.next = head; ListNode *pre = &dummy; ListNode *cur = head; ListNode *tmp; int len = 0; while (cur) {len++; Cur = cur->next; } while (len>=k) {cur = pre->next; TMP = cur->next; for (int i=1;i<k;i++) {Cur->next = tmp->next; Tmp->next = pre->next; Pre->next = tmp; TMP = cur->next; } pre = cur; Len-= k; } return dummy.next; }};
Leetcode:reverse Nodes in K-group