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.
Example:
1 |
|
Note:
- Only constant extra memory is allowed.
- You may not alter the values in the list’s nodes, only nodes itself may be changed.
Related Topics: Linked List
解題邏輯與實作
這題是 Swap Nodes in Pairs 的進階題,不同於上一題是兩兩交換,這一題是以每 k 個節點為一組翻轉鏈結串列。
不過這題在實做時,卡了我老久,主要是我試圖在一個迴圈把所整個翻轉過程,連同頭尾的指標一併搞定,所以寫起來超級的不順手。後來在這一篇中看到它的整理,這才總算讓我的思考清晰了許多:
1 |
|
1 |
|