LeetCode 25. K 個一組翻轉連結串列 | Python
阿新 • • 發佈:2020-05-03
### 25. K 個一組翻轉連結串列
---
題目來源:[https://leetcode-cn.com/problems/reverse-nodes-in-k-group](https://leetcode-cn.com/problems/reverse-nodes-in-k-group)
#### 題目
---
給你一個連結串列,每 k 個節點一組進行翻轉,請你返回翻轉後的連結串列。
k 是一個正整數,它的值小於或等於連結串列的長度。
如果節點總數不是 k 的整數倍,那麼請將最後剩餘的節點保持原有順序。
**示例:**
給你這個連結串列:1->2->3->4->5
當 k = 2 時,應當返回: 2->1->4->3->5
當 k = 3 時,應當返回: 3->2->1->4->5
說明:
- 你的演算法只能使用常數的額外空間。
- 你不能只是單純的改變節點內部的值,而是需要實際進行節點交換。
#### 解題思路
---
**思路:迭代、翻轉連結串列**
具體思路:
- 首先要確保翻轉的範圍,這個是由題目中提及的 k 來控制;
- 關於連結串列的翻轉,要注意前驅和後繼的問題,防止指向錯誤,這裡也為了將翻轉後的連結串列與後續進行連線;
- 定義 pre 和 tail,pre 表示待翻轉連結串列部分的前驅,tail 表示末尾;
- 上面的 tail 經由 k 控制到達末尾;
- 翻轉連結串列,將翻轉後的部分與後續進行拼接;
- 注意:根據題意,當翻轉部分的長度小於 k 時,這個時候不做處理。
具體的程式碼實現如下。
#### 程式碼實現
---
```python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
if head == None and head.next == None and k < 2:
return head
# 定義哨兵節點
dummy = ListNode(0)
# 指向節點
dummy.next = head
# 定義前驅後繼節點
pre = dummy
tail = dummy
# 控制 tail 到待翻轉連結串列部分的末尾
while True:
count = k
while count > 0 and tail != None:
count -= 1
tail = tail.next
# 到達尾部時,長度不足 k 時,跳出迴圈
if tail == None:
break
# 這裡用於下次迴圈
head = pre.next
# 開始進行翻轉
while pre.next != tail:
tmp = pre.next
pre.next = tmp.next
tmp.next = tail.next
tail.next = tmp
# 重置指標
pre = head
tail = head
return dummy.next
```
#### 實現結果
---
![實現結果](https://img2020.cnblogs.com/other/2016405/202005/2016405-20200503190428972-1170870067.png)
---
> 以上就是使用迭代,根據題目提供的 k 值確定翻轉連結串列部分,在內部實現翻轉,進而解決《25. K 個一組翻轉連結串列》的主要內容。其中注意要定義連結串列的前驅和後繼,防止指向