0. 链表 不太会,链表知识待补课
1. 如果head is None,返回head
2. 将链表首位相接变为循环链表并得到链表长度
3. 从原head位开始寻找新head(if index == length-k)
4. 如果当前位的下一位是新头部,储存新head,并切断当前node与node.next(新head)之间的link。返回新head
获取单链表的倒数第 N + 1 与倒数第 N 个节点
将倒数第 N + 1 个节点的 next 指向 null
将链表尾节点的 next 指向 head
返回倒数第 N 个节点
例如链表 A -> B -> C -> D -> E 右移 2 位,依照上述步骤为:
获取节点 C 与 D
A -> B -> C -> null, D -> E
D -> E -> A -> B -> C -> nul
返回节点 D
注意:假如链表节点长度为 len,
则右移 K 位与右移动 k % len 的效果是一样的
就像是长度为 1000 米的环形跑道,
你跑 1100 米与跑 100 米到达的是同一个地点
获取链表的长度
k = k % 链表的长度
获取倒数第k + 1,倒数第K个节点与链表尾节点
倒数第k + 1个节点.next = null
链表尾节点.next = head
return 倒数第k个节点
代码
classSolution:defrotateRight(self, head: ListNode, k:int)-> ListNode:# if head is null, return headifnot head:return head
# Get length and connect the last and head to change NodeList to a circular NodeList
length =1
newNode = head
while(newNode.next):
newNode = newNode.next
length +=1
newNode.next= head
# get real cut index
k = k % length
# find new head
index =0
returnNode =Nonewhile(True):if index == length-k:
returnNode = newNode.next
newNode.next=Nonereturn returnNode
index +=1
newNode = newNode.nextclassSolution:defrotateRight(self, head: ListNode, k:int)-> ListNode:if head:
p1 = head
p2 = head
count =1
i =0while i < k:if p2.next:
count +=1
p2 = p2.nextelse:
k = k % count
i =-1
p2 = head
i +=1while p2.next:
p1 = p1.next
p2 = p2.nextif p1.next:
tmp = p1.nextelse:return head
p1.next=None
p2.next= head
return tmp