简繁EN

LeetCodeNo. 112

【LeetCode with Python】 61. Rotate List

目錄

題目

原題頁面:https://leetcode.com/problems/rotate-list/
題目型別:Linked List, Two Pointers
難度評價:Medium
類似題目:(E) Rotate Array

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.


分析

這類連結串列倒置,或連結串列區域性倒置的題目,都是大學資料結構課程的日常題目。一般要注意三點:

  1. 在必要的head/tail處設定指標,便於操作;
  2. 注意當節點數n為0、1、2等時的特殊情況下的處理,記得檢查指標是否為None;
  3. 有時候head或tail需要特殊處理,此時可以通過增加一個new_head或new_tail,使得head或tail可以被當成普通節點來處理。

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution:
# @param head, a ListNode
# @param k, an integer
# @return a ListNode
def rotateRight(self, head, k):
if None == head or None == head.next:
return head
n = 0
cur = head
while None != cur:
n += 1
cur = cur.next
# k may be larger than the length; only k % n matters.
k %= n
if 0 == k:
return head
# The new tail is n - k - 1 steps after head.
steps = n - k - 1
cur_head = head
cur = head
while steps > 0:
cur = cur.next
steps -= 1
cur_tail = cur
cur_head = cur.next
cur = cur_head
while None != cur.next:
cur = cur.next
cur.next = head
cur_tail.next = None
return cur_head

本文地址:https://xnerv.wang/zh-tw/leetcode-rotate-list/