【LeetCode每天一题】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
思路
对于链表类的题目最重要的就是指针的控制,因此对于这道题我的思路就是我们先找到倒数第K个节点前一个节点的位置,并先将链表尾部指针指向头指针,然
后将头指针指向倒数第K个节点,最后对倒数K节点上一个指针赋值为None。时间复杂度为O(n), 空间复杂度为O(1)
图示步骤
解决代码
1 class Solution(object):
2 def rotateRight(self, head, k):
3 """
4 :type head: ListNode
5 :type k: int
6 :rtype: ListNode
7 """
8 if not head or k < 0: # 为空或者K小于0直接返回
9 return head
10 length, tem = 0, head
11
12 while tem: # 求出链表的长度
13 tem, length = tem.next, length + 1
14
15 k = k % length # 防止K的长度大于链表的长度
16 fast, slow = head, head
17 while k > 0: # 快指针先走K步
18 fast, k = fast.next, k-1
19
20 while fast.next: # 两个指针同时动
21 slow, fast = slow.next, fast.next
22 fast.next = head # 进行指针交换操作得到结果
23 head = slow.next
24 slow.next = None
25 return head
26