Leetcode 61

Question

Solution

首先需要考虑链表的总长度,因为需要用它来计算执行了多少个循环。通过k%length来判断实际需要执行的部分。创建两个指针,然后将指向末位元素的指针的next指向head,将前面的指针next设为None。这个时候,需要注意的是,head已经不是整个链表的head了,需要调整。

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
32
33
34
35
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
if not head:
return
if head.next == None:
return head
if k == 0:
return head
pointer = head
length = 1
while pointer.next:
pointer = pointer.next
length += 1

roate = k % length
if roate == 0:
return head
pre = cur = head
while cur.next:
if roate:
roate -= 1
else:
pre = pre.next
cur = cur.next
temp = pre.next
pre.next = None
cur.next = head
head = temp
return head