问题描述:
将一个单链表,向右翻转k次,注意k可能大于链表长度。
原文链接
# python3
# 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 k==0 or head==None:return head
current,tail = head,head
N=1
while tail.next!=None:
N+=1
tail = tail.next
k = k%N #当k大于链表长度时,等效于翻转K%N次
tail = head
i=0
while i<k:
tail = tail.next
i+=1
while tail.next!=None:
tail = tail.next
current = current.next
tail.next = head
head = current.next
current.next=None
return head
网友评论