Given a list, rotate the list to the right by k places, where k is non-negative.
Example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class ListNode2(ListNode):
def __init__(self,x):
self.val = x
self.next = None
def append(self, dataOrNode):
item = None
if isinstance(dataOrNode, ListNode):
item = dataOrNode
else:
item = ListNode(dataOrNode)
if not self:
self = item
else:
node = self
while node.next:
node = node.next
node.next = item
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
res = []
root = head
if head == None:return None
while root:
res.append(root.val)
root = root.next
k = k%len(res)
if k == 0:return head
res = res[len(res)-1-k::-1] + res[:len(res)-1-k:-1]
res = res[::-1]
p = ListNode2(res[0])
for i in res[1:]:
p.append(i)
return p