【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         

 

 

 

 



转载于:https://www.cnblogs.com/GoodRnne/p/10749297.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值