码迷,mamicode.com
首页 > 其他好文 > 详细

61. Rotate List

时间:2019-04-04 23:08:26      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:新建   output   tno   head   link   style   思路   ext   exp   

1. 原始题目

Given a linked list, rotate the list to the right by k places, where k is non-negative.

Example 1:

Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL

Example 2:

Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL

2. 题目理解

给定一个链表,旋转链表,将链表每个节点向右移动 个位置,其中 是非负数。

坑:空列表

 

3. 解题

思路:先遍历一遍链表得到表长n。然后尾部指向头部,实现循环列表。其实向右移k个距离,k可以很大,但是k%n正好是对应着新表头的位置。这时直接将表头前一个元素指向None,并返回新表头即可。

 1 class Solution:
 2     def rotateRight(self, head: ListNode, k: int) -> ListNode:
 3         if k==0:
 4             return head
 5         if not head or not head.next:
 6             return head
 7         
 8         i = head     
 9         len_list = 1
10         while(i.next):
11              i = i.next
12              len_list += 1          # 得到表长
13              
14         i.next = head
15         sign = len_list - k%len_list      # 记录从前向后需要便利多长距离才能找到新表头
16         
17         for i in range(sign-1):
18             head = head.next              # 得到新表头前一个元素
19         i = head.next        # i为新表头  
20         head.next = None     #  别忘了表尾置空
21         
22         return i

 

4. 验证

 1 # 新建链表1
 2 listnode1 = ListNode_handle(None)
 3 s1 = [1,2,3,4,5,6,8,999,666]
 4 for i in s1:
 5     listnode1.add(i)
 6 listnode1.print_node(listnode1.head)
 7 
 8 
 9 s = Solution()
10 head = s.rotateRight(listnode1.head, 6)
11 listnode1.print_node(head)

1 2 3 4 5 6 8 999 666
4 5 6 8 999 666 1 2 3

 

 

61. Rotate List

标签:新建   output   tno   head   link   style   思路   ext   exp   

原文地址:https://www.cnblogs.com/king-lps/p/10657396.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!