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.
Subscribe to see which companies asked this question
先算出list的长度,然后再用最朴素的想法来完成
class Solution(object):
def rotateRight(self, head, k):
if k == 0 or head == None:
return head
if not head.next:
return head
h = head
l = 0
while h:
l += 1
tail = h
h = h.next
#print l
k = k % l
if k == 0:
return head
count = 0
h = head
new_h = ListNode(0)
while count < l - k:
prv = h
h = h.next
count += 1
new_h.next = h
tail.next = head
prv.next = None
return new_h.next

本文介绍了一种链表操作的方法——链表右旋。通过计算链表长度并利用基本的链表操作技巧,实现了将链表向右旋转k个位置的功能。
440

被折叠的 条评论
为什么被折叠?



