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
return
题目解释:
给定一个链表,将链表末尾的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
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->NULLand 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
相关文章推荐
- 【LeetCode-面试算法经典-Java实现】【061-Rotate List(旋转单链表)】
- C实现 LeetCode->Rotate List(双指针大法)(单链表 部分旋转)
- Leetcode 61. Rotate List (旋转链表)
- leetCode 61.Rotate List (旋转链表) 解题思路和方法
- [LeetCode] 61. Rotate List 旋转链表
- Leetcode Rotate List 旋转链表
- LeetCode:Rotate List(旋转链表)
- 链表系列-把链表向右旋转k个位置LeetCode#61. Rotate List
- leetCode 61.Rotate List (旋转链表) 解题思路和方法
- leetcode 【Rotate List 】python 实现
- leetcode 61. Rotate List 向右旋转k个元素 + 链表环遍历
- LeetCode 61. Rotate List(旋转链表)
- LeetCode-Rotate List-旋转链表-旋转操作和链表
- LeetCode 61. Rotate List(Python详解及实现)
- LeetCode(Rotate List) 旋转链表
- LeetCode-----61. Rotate List(循环旋转链表)
- 【LeetCode题解】61_旋转链表(Rotate-List)
- LeetCode 61. Rotate List---Python实现
- [Leetcode] Rotate list 旋转链表
- leetcode解题61. Rotate List java版(旋转链表)