leetcode笔记--Rotate List
来源:互联网 发布:js 如何遍历数组对象 编辑:程序博客网 时间:2024/06/05 19:43
题目:难度(Medium)
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.
Tags:Linked List Two Pointers
Similar Problems:(E) Rotate Array
分析:k是一个非负整数,将链表向右旋转k个元素,即将右边k个节点拿到链表的前面,也就是说把链表的前len-k+1个节点拿到链表的后面去。如果k%len == 0的话,链表旋转以后还是会还原,则直接返回链表即可,否则,将链表分成2段,前一段为len-k+1个节点,p为第1段的尾节点,q为整个链表的尾节点也是第2段的尾节点,将第2段与第1段链接起来:q.next = head,那么新的头节点应该为第2段的头节点位置即p.next,新的尾节点即为第1段的尾节点p,即p.next = None
代码实现:
# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = Noneclass Solution(object): def rotateRight(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ if head is None: return None #找到新的头节点、尾节点p,断开新的尾节点与新头节点(新尾节点是新头节点的前驱),连上旧的尾节点q与旧头节点 #新的头节点的位置是正向第len-k+1的位置 len = self.getLenOfSinglyLinkedList(head) #k == 0 或者 k == len 或者 k是len的整数倍 if k%len == 0: return head pos = len - k%len count = 1 p = head while count < pos: p = p.next count+=1 #此时p为新的尾节点 #继续找到旧尾节点位置 q = p while q.next is not None: q = q.next #此时q为旧尾节点位置 q.next = head head = p.next p.next = None return head def getLenOfSinglyLinkedList(self, head): p = head len = 0 while p: p = p.next len+=1 return len
0 0
- leetcode笔记--Rotate List
- [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
- LeetCode 61: Rotate List
- iOS开发的一些奇巧淫技
- fuser 命令
- 对之前所提到的sigar的介绍进行补充
- Udemy - Build Apps with React Native
- Ubuntu下找不到php5,phpize等可执行程序的解决办法
- leetcode笔记--Rotate List
- Failure [INSTALL_FAILED_ALREADY_EXISTS]
- 简谈高通Trustzone的实现
- poj seek the name,seek the fame
- ProjectOne(02) - 创建一个package.json文件
- 如何充分利用管理咨询提高企业创新能力
- Ruby排序
- mac 下 zsh配置
- IOS 设置支付按键方形角为圆弧