【Leetcode】【python】Rotate List
2017-10-13 06:58
429 查看
题目大意
将一个链表中的元素向右旋转k个位置。解题思路
参考:http://www.cnblogs.com/zuoyuan/p/3785465.html解题思路:循环右移一条链表,比如k=2,(1,2,3,4,5)循环右移两位变为(4,5,1,2,3)。由于k值有可能比链表长度大很多,所以先要用一个count变量求出链表的长度。而k%count就是循环右移的步数。
代码
class Solution(object): def rotateRight(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ if k == 0: return head if head == None: return head dummy = ListNode(0) dummy.next = head p = dummy count = 0 while p.next: # 这里实际上是从0开始数,数到4就结束,正好5个。 # print p.val p = p.next count += 1 step = count - ( k % count ) # 此时p是最后一个数5,p.next指向null p.next = dummy.next # p.next指向第一个数,这样p就是0,1,2,3,4,5,1,2,3,4,5 print step for i in range(0, step): p = p.next # 此时p是最后一个未翻转的数3,将其下一个数,放到head节点 head = p.next # 此时head是4,5,1,2,3,4,5 p.next = None return head
总结
此题不甚理解,应该是题目有问题,差评率有点高相关文章推荐
- [Leetcode]61. Rotate List @python
- leetcode Rotate list (链表旋转)的python实现
- [leetcode]Rotate List @ Python
- leetcode 【Rotate List 】python 实现
- LeetCode 61. Rotate List(Python详解及实现)
- [LeetCode]题解(python):061-Rotate List
- LeetCode 61 — Rotate List(C++ Java Python)
- [LeetCode]Rotate List@python
- 【LEETCODE】61- Rotate List [Python]
- Rotate List Python Leetcode
- LeetCode 61. Rotate List---Python实现
- 【leetcode】189. Rotate Array(Python & C++)
- LeetCode 148 — Sort List(C++ Java Python)
- leetcode[61]Rotate List
- Leetcode:61. Rotate List
- 【LEETCODE】147- Insertion Sort List [Python]
- leetcode_107. Binary Tree Level Order Traversal II 二叉树层次遍历,利用python的list特性实现队列功能
- leetcode Rotate List
- Rotate List - Leetcode
- LeetCode || Rotate List