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
Given this linked list:
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
<Solution>
這題是 Swap Nodes In Pairs 的進階題
這次可以指定要幾個為一組來 reverse,難度提高了不少
這次使用遞迴來解(參考資料)
解題想法是
- head 指向這一組的第一個元素,end 指向這一組最後一個元素的 next
- 針對每一組做 reverse,回傳一個 new head
- 在 reverse 完後,head 會被移到新位置,但 head 還是指向同樣的元素
- 這時候用 head->next 去接下一組會回傳的 new head
c++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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) { | |
ListNode *end = head; | |
for(int i = 0; i < k; i++) { | |
if(!end) { | |
return head; | |
} | |
end = end->next; | |
} | |
//> reverse group | |
ListNode *new_head = reverse(head, end); | |
//> recursive solving | |
head->next = reverseKGroup(end, k); | |
return new_head; | |
} | |
ListNode *reverse(ListNode *head, ListNode *tail) { | |
ListNode *reverseHead = tail; | |
while(head != tail) { | |
ListNode *tmp = head->next; | |
head->next = reverseHead; | |
reverseHead = head; | |
head = tmp; | |
} | |
return reverseHead; | |
} | |
}; |
kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Example: | |
* var li = ListNode(5) | |
* var v = li.`val` | |
* Definition for singly-linked list. | |
* class ListNode(var `val`: Int) { | |
* var next: ListNode? = null | |
* } | |
*/ | |
class Solution { | |
fun reverseKGroup(head: ListNode?, k: Int): ListNode? { | |
var start = head | |
var end = head | |
IntRange(1,k).forEach { | |
if(end == null) { | |
return head | |
} | |
end = end?.next | |
} | |
val newHead = reverse(start, end) | |
head?.next = reverseKGroup(end, k) | |
return newHead | |
} | |
fun reverse(start: ListNode?, end: ListNode?): ListNode? { | |
var startNode = start | |
var newHead = end | |
while(startNode != end) { | |
val next = startNode?.next | |
startNode?.next = newHead | |
newHead = startNode | |
startNode = next | |
} | |
return newHead | |
} | |
} |
沒有留言:
張貼留言