代码一:
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
tail = head
res = []
while tail:
res.append(tail.val)
tail = tail.next
if len(res) == 0:
return head
k = k % len(res)
while k > 0:
temp = res.pop()
res.insert(0, temp)
k -= 1
pre = node = ListNode(0)
for i in range(len(res)):
node.next = ListNode(0)
node.next.val = res[i]
node = node.next
return pre.next
代码二:
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if k==0:
return head
node = head
len = 0
while node:
len += 1
node = node.next
if len<2 or len == k or k%len==0:
return head
k %= len
cur, tail = head, head
precur = ListNode(0)
while k > 1 and tail.next:
tail = tail.next
k -= 1
while tail.next:
precur = cur
cur = cur.next
tail = tail.next
tail.next = head
precur.next = None
head = cur
return head