您的位置:首页 > 编程语言 > Python开发

leetcode Rotate list (链表旋转)的python实现

2017-05-12 18:35 375 查看
题目如下:

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个结点移动到最前面。

思路:

采用 fast-slow 指针的方法,令fast指针先移动k步,步长为1。然后两个指针同时移动,当fast指针到达最末尾时,将fast指向head,slow指向None,则完成旋转。

注:题目中的k有可能大于链表总长度,因此需要对k取模。

class Solution(object):
def rotateRight(self, head, k):
if not head or not head.next or k==0:
return head
ListLen = 0
p = head
while(p):
ListLen+=1
p = p.next
k = k%ListLen
if k==0:
return head
p = head
while(k>0):
k -=1
p = p.next
slow = head
fast = p
while fast.next:
slow = slow.next
fast = fast.next

new_head = slow.next
fast.next = head
slow.next = None
return new_head
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: