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++
kotlin
沒有留言:
張貼留言