【LeetCode】025. 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.
k is a positive integer and is 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.
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
題解:
反轉鏈表最適合遞歸去解決。首先想到的是判斷當前鏈表是否有k個數可以反轉,如果沒有k個數則返回頭結點,否則反轉該部分鏈表並遞歸求解後來的反轉鏈表部分。為數不多的Hard 題AC
Solution 1
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* reverseKGroup(ListNode* head, int k) { 12 ListNode* cur = head, *tail = nullptr;13 for(int i = 0; i < k; ++i) { 14 if (!cur) 15 return head; 16 if (i == k - 1) 17 tail = cur; 18 cur = cur->next; 19 } 20 21 reverse(head, tail); 22 head->next = reverseKGroup(cur, k); 23 24 return tail; 25 } 26 27 void reverse(ListNode* head, ListNode* tail) { 28 if (head == tail) 29 return; 30 ListNode* pre = head, *cur = pre->next; 31 while(cur != tail) { 32 ListNode* tmp = cur->next; 33 cur->next = pre; 34 pre = cur; 35 cur = tmp; 36 } 37 cur->next = pre; 38 } 39 };
簡化版:
1 class Solution { 2 public: 3 ListNode* reverseKGroup(ListNode* head, int k) { 4 ListNode *cur = head; 5 for (int i = 0; i < k; ++i) { 6 if (!cur) return head; 7 cur = cur->next; 8 } 9 ListNode *new_head = reverse(head, cur); 10 head->next = reverseKGroup(cur, k); 11 return new_head; 12 } 13 ListNode* reverse(ListNode* head, ListNode* tail) { 14 ListNode *pre = tail; 15 while (head != tail) { 16 ListNode *t = head->next; 17 head->next = pre; 18 pre = head; 19 head = t; 20 } 21 return pre; 22 } 23 };
轉自:Grandyang
首先遍歷整個鏈表確定總長度,如果長度大於等於k,那麽開始反轉這k個數組成的部分鏈表。交換次數為k-1次,反轉後,更新剩下的總長度,叠代進行。
Solution 2
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* reverseKGroup(ListNode* head, int k) { 12 ListNode dummy(-1); 13 dummy.next = head; 14 ListNode* pre = &dummy, *cur = pre; 15 int len = 0; 16 while (cur->next) { 17 ++len; 18 cur = cur->next; 19 } 20 while (len >= k) { 21 cur = pre->next; 22 for (int i = 0; i < k - 1; ++i) { 23 ListNode* tmp = cur->next; 24 cur->next = tmp->next; 25 tmp->next = pre->next; 26 pre->next = tmp; 27 } 28 pre = cur; 29 len -= k; 30 } 31 32 return dummy.next; 33 } 34 };
【LeetCode】025. Reverse Nodes in k-Group