leetcode -- Rotate List -- 重点
来源:互联网 发布:好听有内涵的名字知乎 编辑:程序博客网 时间:2024/04/27 12:23
https://leetcode.com/problems/rotate-list/
这里思路很简单。但是要注意,k可以大于len(linkedlist). 要求得长度之后取mod。还有就是这个rotate,不需要把rotate部分逆置。
def rotateRight(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ if not head or not head.next: return head #calculate the length p = head count = 0 while p: p = p.next count += 1 k = k % count #print (count,k) if k == 0: return head i,j = head,head pre_i = None for x in xrange(k-1): j = j.next while j.next: pre_i = i i, j = i.next, j.next if i == head: return head else: new_head, new_end = i,j new_end.next = head pre_i.next = None return new_head
由于一开始看错题目,以为rotate的部分要逆置。所以这里还是post出逆置的code。
# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = Noneclass Solution(object): def reverse(self, head): org_head = head cur = head.next pre = head pre.next = None while cur: tmp = cur.next cur.next = pre pre, cur =cur, tmp return pre, org_head def rotateRight(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ if not head or not head.next: return head #calculate the length p = head count = 0 while p: p = p.next count += 1 k = k % count print (count,k) if k == 0: return head i,j = head,head pre_i = None for x in xrange(k-1): j = j.next while j.next: pre_i = i i, j = i.next, j.next if i == head: return self.reverse(i)[0] else: new_head, new_end = self.reverse(i) new_end.next = head pre_i.next = None return new_head
0 0
- leetcode -- Rotate List -- 重点
- leetcode -- Rotate Array -- 重点
- [leetcode][list] Rotate List
- LeetCode: Rotate List
- LeetCode Rotate List
- LeetCode : Rotate List
- [Leetcode] Rotate List
- [LeetCode] Rotate List
- [leetcode] Rotate List
- leetcode 70: Rotate List
- [Leetcode] Rotate List
- 【leetcode】Rotate List
- [LeetCode]Rotate List
- [leetcode]Rotate List
- LeetCode-Rotate List
- [leetcode] Rotate List
- LeetCode - Rotate List
- LeetCode:Rotate List
- Stream API:有状态的转换
- Ceph Storange Cluster----配置
- 安装git
- 以太网为什么要限制最小帧长?
- 表单验证
- leetcode -- Rotate List -- 重点
- Unity3D-Unity Remote
- ActiveMQ 故障处理
- 开贴纪念
- 让UIImageView适应图片的大小
- JAVA面向对象编程上重点总结
- 测试用例设计--因果图
- 71道经典Android面试题和答案
- 批量导入po接口生成po的代码