# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head or not head.next:
return head
dummyHead = ListNode(0)
dummyHead.next = head
pre = dummyHead
tail = head
sum = 1
while tail.next:
pre = pre.next
tail = tail.next
sum += 1
count = k % sum
while count:
pre.next = tail.next
tail.next = dummyHead.next
dummyHead.next = tail
pre , tail = self.getTail(dummyHead.next)
return dummyHead.next
def getTail(self,head):
pre = head
tail = head.next
while tail.next:
pre = tail
tail = tail.next
return pre ,tail
def creatList(self,l):
dummyHead = ListNode(0)
pre = dummyHead
for i in l:
pre.next = ListNode(i)
pre = pre.next
return dummyHead.next
def printList(self,head):
cur = head
while cur:
print cur.val
cur = cur.next
l1 = [1,2,3,4,5,6]
k = 2
s = Solution()# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head or not head.next:
return head
dummyHead = ListNode(0)
dummyHead.next = head
pre = dummyHead
tail = head
sum = 1
while tail.next:
pre = pre.next
tail = tail.next
sum += 1
count = k % sum
# pre.next = tail.next
# tail.next = dummyHead.next
# dummyHead.next = tail
#
# self.printList(dummyHead.next)
#
# pre, tail = self.getTail(dummyHead.next)
#
# # print pre.val
# # print tail.val
#
# pre.next = tail.next
# tail.next = dummyHead.next
# dummyHead.next = tail
#
# self.printList(dummyHead.next)
while count > 0:
pre.next = tail.next
tail.next = dummyHead.next
dummyHead.next = tail
pre , tail = self.getTail(dummyHead.next)
count -= 1
return dummyHead.next
def getTail(self,head):
pre = head
tail = head.next
while tail.next:
pre = tail
tail = tail.next
return pre ,tail
def creatList(self,l):
dummyHead = ListNode(0)
pre = dummyHead
for i in l:
pre.next = ListNode(i)
pre = pre.next
return dummyHead.next
def printList(self,head):
cur = head
while cur:
print cur.val
cur = cur.next
l1 = [1,2,3,4,5]
k = 2
s = Solution()
head = s.creatList(l1)
s.printList(head)
s.rotateRight(head,2)