61. Rotate List 把最后一个节点插入头节点后
2020-05-25 本文已影响0人
羲牧
首先需要发现,k与链表长度N的关系。
其次,重复执行“把最后一个节点插入头节点后”
生成带头节点使得操作变得简单
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
if k == 0 or head is None or head.next is None:
return head
H = ListNode()
H.next = head
p = H
length = 0
while p.next:
length += 1
p = p.next
k = k % length
for i in range(k):
p = H.next
q = H
while p.next:
q = p
p = p.next
p.next = H.next
H.next = p
q.next = None
return H.next