题目分析:
这一题是让链表的最后几位挪(移动)到最前面,我们先遍历出总长度。若要移动后两个,我们把首尾连起来,我们就往后移动length - 2位后断开即可。
测试代码(非提交代码):
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def print_listNode(listNode: ListNode):
bf_listNode = listNode
while True:
if bf_listNode.next != None:
print(bf_listNode.val, end='-->')
bf_listNode = bf_listNode.next
else:
break
print(bf_listNode.val)
class Solution:
def rotateRight(self, head, k):
if head == None or k == 0:
return head
p = ListNode(0)
p.next = head
length = 0
while p.next:
p = p.next
length += 1
p.next = head
k = length - (k % length)
for i in range(k):
p = p.next
head = p.next
p.next = None
return head
l1_1 = ListNode(1)
l1_2 = ListNode(2)
l1_3 = ListNode(3)
l1_4 = ListNode(4)
l1_5 = ListNode(5)
l1_1.next = l1_2
l1_2.next = l1_3
l1_3.next = l1_4
l1_4.next = l1_5
print_listNode(l1_1)
print_listNode(Solution().rotateRight(l1_1, 2))
提交代码:
class Solution:
def rotateRight(self, head, k):
if head == None or k == 0:
return head
p = ListNode(0)
p.next = head
length = 0
while p.next:
p = p.next
length += 1
p.next = head
k = length - (k % length)
for i in range(k):
p = p.next
head = p.next
p.next = None
return head