题意:Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
思路:这题我开始的想法分别用两个指针,一个先移k位,再两个同时向前移,比如对于上面那个例子,slow指向3,fast指向5,再把slow断开,然后用fast指向head就可以了,但是这题其实一个问题,就是k的取值,对于1->2,如果k取3的话,最后的答案应该是2->1,所以对于我这种方法的话,就要先遍历一次列表来求长度,再求余,代码会显得稍微繁琐一点:
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head:
return head
fast = slow = head
cnt = 0
while fast:
cnt += 1
fast = fast.next
fast, k = head, k%cnt
if not k%cnt:
return head
while fast.next:
if k == 0:
slow = slow.next
else:
k -= 1
fast = fast.next
new_head = slow.next
slow.next = None
fast.next = head
return new_head
当然,还看到有一种方法,是直接遍历到结尾,求出长度len,然后让首尾连接成一个环链表,然后再向前移动len-k%len长度,再把next打断就可以了:
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
n, cur = 1, head
while cur.next:
cur = cur.next
n += 1
cur.next = head
cur, tail = head, cur
for _ in xrange(n - k % n):
tail = cur
cur = cur.next
tail.next = None
return cur