150強訪談簡單

K組中的反向節點

“K 組中的反向節點”問題的詳細指南和 Python 實作。

問題陳述

簡單

給定一個鍊錶的頭,每次反轉鍊錶 k 的節點,並傳回修改後的鍊錶。

k是正整數且小於或等於鍊錶的長度。如果節點數不是 k 的倍數,則最終留下的節點應保持原樣。

您不能更改清單節點中的值,只能更改節點本身。

連結列表表示為 Python 列表。實作函數 reverseKGroup(head: list, k: int) -> list

約束條件
  • The number of nodes in the list is n
  • 1 <= k <= n <= 5000
  • 0 <= Node.val <= 1000

範例

Example 1
Input
[1,2,3,4,5], 2
Output
[2,1,4,3,5]
Explanation

Reverse in groups of 2: [1,2] becomes [2,1], [3,4] becomes [4,3], and [5] stays as is.

Example 2
Input
[1,2,3,4,5], 3
Output
[3,2,1,4,5]
Explanation

Reverse in groups of 3: [1,2,3] becomes [3,2,1], and [4,5] has fewer than 3 nodes so it stays.

Need a Hint?
考慮使用特定於連結清單的資料結構,例如集合或堆。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。