LeetCode 61. Rotate List(Python详解及实现)
来源:互联网 发布:淘宝网家电电器品种 编辑:程序博客网 时间:2024/04/25 13:08
【题目】
Given a list, rotate the list to the rightby 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个结点移动到最前面。
【思路】
方法一:
先遍历一次求长度,然后再求模得到真正右移数量
方法二:
采用bef、af 指针的方法(前后指针),令bef指针先移动k步,步长为1。然后两个指针同时移动,当bef指针到达最末尾时,将bef指向head,af指向None,则完成旋转。
注:题目中的k有可能大于链表总长度,因此需要对k取模。
【Python实现】
方法一:
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if head == None or k == 0:
return head
dummy = ListNode(0)#创建一个虚假的头结点
dummy.next = head #虚假头结点指向head
#计算链表长度
count = 0
p = dummy
while p.next != None:
p = p.next#最终P将指向尾节点
count += 1
p.next = dummy.next#将尾结点指向头结点,形成环形
#求真实的右移数量
right = count - k % count
p = dummy.next#指向head
for i in range(1,right):#i = 1 时,p为链表的第2个数据
p = p.next
head = p.next#移动后的头结点
p.next = None
return head
方法二:
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if head == None or head.next == None or k == 0:
return head
count = 0
p = head
while(p):
count += 1
p = p.next
k = k % count#真实旋转值k
if k == 0:
return head
p = head
while(k > 0):#执行完p为链表第k+1个结点
k -= 1
p = p.next
af = head #af为头结点
bef = p #bef为当前p
while bef.next: #将bef移到链表尾结点的同时,af也向尾结点方向移
af = af.next #bef移到尾结点的同时,af指向旋转后的尾结点
bef = bef.next
new_head = af.next #旋转后的尾结点的下一个结点即为新链表的头结点
bef.next = head #原链表的尾结点指向原头结点
af.next = None #旋转后的尾结点指向None
return new_head
- LeetCode 61. Rotate List(Python详解及实现)
- [Leetcode]61. Rotate List @python
- leetcode Rotate list (链表旋转)的python实现
- Rotate List Python Leetcode
- 【Leetcode】【python】Rotate List
- 【LeetCode】61. Rotate List解法及分析
- 61. Rotate List(python)
- 【LeetCode with Python】 Rotate List
- 【LEETCODE】61- Rotate List [Python]
- [LeetCode]61.Rotate List
- LeetCode --- 61. Rotate List
- [Leetcode] 61. Rotate List
- [leetcode] 61.Rotate List
- [leetcode] 61. Rotate List
- leetcode 61. Rotate List
- LeetCode 61. Rotate List
- [leetcode] 61. Rotate List
- 61. Rotate List LeetCode
- 最新仿微信红包扫雷接龙牛牛源码和安装教程
- 1021. 个位数统计 (15)
- Python 匿名函数
- 百度地图删除指定标注(或其他覆盖物)
- Excel—“撤销工作表保护密码”的破解并获取原始密码
- LeetCode 61. Rotate List(Python详解及实现)
- UCC输入文件处理
- lua教程十---使用Lua CJSON库进行encode与decode操作完成对Json数据转化
- 从csv中读数据,并写到csv中
- Android性能优化总结
- poj1017
- java.net.SocketException: Permission denied: connect
- 我为什么要写编程教程?
- log4j的几种常用配置