Rotate List-源码
一.题目描述-Rotate List
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
原题链接: https://leetcode.com/problems/rotate-list/
二.解题思路
2.1 思路一(Naive)——每次循环右移一位+做k次循环
考虑到要求循环右移k位,那么只需要先编写一个每次移动一位的函数,然后调用k次即可。但是显然这种方法蠢萌蠢萌的,使用后实测发现Time Limit Exceeded。原因是k可能会很大,当len(list)也很长时,总是这样循环遍历效率极低。
2.2 思路二——循环右移k次,找关键中断点,调整头尾指针
-
观察发现,当进行循环右移时,找关键点应当是从右往左(也就是从尾到头)查找,以Example1 为例:
Input: 1->2->3->4->5->NULL, k = 2 从右往左查找,第2位是’4‘,所以此处’4‘就是新链表的头节点,’3‘是新链表的尾节点,只需要重新调整链表中指针指向即可。
-
考虑到可能出现k > len(list)的情况,此时只需简单处理,令k = k % len(list)即可解决。
-
回顾步骤1和2会发现当前的解决方法是从尾部往头部找关键点,对于单向链表而言,想要实现这一点比较麻烦。所以我们可以使用等价的向左移位来代替向右移位。具体而言向右循环移动** k 次,等价于向左循环移位 len(list)-k **次。向左移位时找关键点只需要就是从头向尾查找,非常方便。
-
具体代码-Python3代码:(C++或者java可以轻易套用此思路进行处理)
class Solution(object