https://leetcode.com/problems/rotate-list/
这里思路很简单。但是要注意,k可以大于len(linkedlist). 要求得长度之后取mod。还有就是这个rotate,不需要把rotate部分逆置。
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head or not head.next: return head
#calculate the length
p = head
count = 0
while p:
p = p.next
count += 1
k = k % count
#print (count,k)
if k == 0: return head
i,j = head,head
pre_i = None
for x in xrange(k-1):
j = j.next
while j.next:
pre_i = i
i, j = i.next, j.next
if i == head:
return head
else:
new_head, new_end = i,j
new_end.next = head
pre_i.next = None
return new_head
由于一开始看错题目,以为rotate的部分要逆置。所以这里还是post出逆置的code。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverse(self, head):
org_head = head
cur = head.next
pre = head
pre.next = None
while cur:
tmp = cur.next
cur.next = pre
pre, cur =cur, tmp
return pre, org_head
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head or not head.next: return head
#calculate the length
p = head
count = 0
while p:
p = p.next
count += 1
k = k % count
print (count,k)
if k == 0: return head
i,j = head,head
pre_i = None
for x in xrange(k-1):
j = j.next
while j.next:
pre_i = i
i, j = i.next, j.next
if i == head:
return self.reverse(i)[0]
else:
new_head, new_end = self.reverse(i)
new_end.next = head
pre_i.next = None
return new_head