1.題目
給你一個鏈表,每 k 個節點一組進行翻轉,請你返回翻轉後的鏈表。
k 是一個正整數,它的值小於或等於鏈表的長度。
如果節點總數不是 k 的整數倍,那麼請將最後剩餘的節點保持原有順序。
示例:
給你這個鏈表:1->2->3->4->5
當 k = 2 時,應當返回: 2->1->4->3->5
當 k = 3 時,應當返回: 3->2->1->4->5
說明:
你的算法只能使用常數的額外空間。
你不能只是單純的改變節點內部的值,而是需要實際進行節點交換。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/reverse-nodes-in-k-group
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
2.題解
遞歸
遞歸實質上就是將原問題分解,我們先判斷鏈表元素數量是否達到k,若未達到,直接返回head即可;
當數量大於等於k時,我們先將pre指針移動到要進行翻轉的最後一個元素的下一個位置,然後我們就開始翻轉第一段鏈表,寫在第二個while中,剩下的部分自然而然就交給reverseKGroup函數去處理,將其返回值接到第一段鏈表的後面。
class Solution
{
public:
ListNode* reverseKGroup(ListNode* head, int k)
{
ListNode *pre = head;
int cnt = 0;
while(pre != nullptr && cnt < k)
{
pre = pre -> next;
cnt++;
}
if(cnt < k)
return head;
ListNode *cur = nullptr;
ListNode *p = head;
while(p != pre)
{
ListNode *temp = p -> next;
p -> next = cur;
cur = p;
p =temp;
}
head -> next = reverseKGroup(pre, k);
return cur;
}
};
官方模擬
class Solution:
# 翻轉一個子鏈表,並且返回新的頭與尾
def reverse(self, head: ListNode, tail: ListNode):
prev = tail.next
p = head
while prev != tail:
nex = p.next
p.next = prev
prev = p
p = nex
return tail, head
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
hair = ListNode(0)
hair.next = head
pre = hair
while head:
tail = pre
# 查看剩餘部分長度是否大於等於 k
for i in range(k):
tail = tail.next
if not tail:
return hair.next
nex = tail.next
head, tail = self.reverse(head, tail)
# 把子鏈表重新接回原鏈表
pre.next = head
tail.next = nex
pre = tail
head = tail.next
return hair.next