简繁EN

LeetCodeNo. 112

[LeetCode with Python] 61. Rotate List

Contents

Problem

Problem page: https://leetcode.com/problems/rotate-list/
Topics: Linked List, Two Pointers
Difficulty: Medium
Similar problems: (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.


Analysis

Problems like this one, where you reverse a linked list or part of one, are routine exercises in a college data structures course. There are generally three things to watch for:

  1. Set up pointers at head/tail as needed to make the list easier to work with.
  2. Handle special cases such as when the number of nodes n is 0, 1, or 2. Remember to check whether a pointer is None.
  3. Sometimes head or tail needs special handling. You can add a new_head or new_tail so you can treat head or tail like any other node.

Code

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

Article link: https://xnerv.wang/en/leetcode-rotate-list/