Đề bài
Bài giải
Code python
# 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
"""
n = 0
c = head
while c:
c = c.next
n += 1
if n == 0: return head
k %= n
if k == 0: return head
slow = fast = head
for _ in xrange(k):
fast = fast.next
while fast.next:
fast = fast.next
slow = slow.next
new_head = slow.next
fast.next = head
slow.next = None
return new_head
Nhờ các bạn submit code ngôn ngữ khác