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. 题目理解
给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
坑:空列表
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