【LeetCode每天一题】Reverse Linked List II(旋转链表II)

Reverse a linked list from position m to n. Do it in one-pass.

  Note: 1 ≤ m ≤ n ≤ length of list.

Example:

Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL

思路

  这到题目和之前的做的链表反转使一样,只不过这里因为是对链表中部分进行反转,所以需要处理的细节稍微会多一些。不过总体来说不是很难。时间复杂度为O(n), 空间复杂度为O(1)。详细参考图示和代码
图示


解决代码

 
 
 1 # Definition for singly-linked list.
 2 # class ListNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution(object):
 8     def reverseBetween(self, head, m, n):
 9         """
10         :type head: ListNode
11         :type m: int
12         :type n: int
13         :rtype: ListNode
14         """
15         res = ListNode(0)       # 使用哨兵节点,简化代码
16         first, res.next, count = res, head, n-m   # 这里使用count变量来记录应该节点的次数   18         while m > 1:         # 找到开始反转节点的前一个节点。
19             first = first.next
20             m-= 1
21             
22         re = one = first.next    # first.next 为开始反转的节点
23         tem = None                  # 辅助节点
24         while one and count >= 0:      # 将需要反转节点的部分进行反转。
25             t = one.next
26             one.next = tem
27             tem = one
28             one = t
29             count -= 1
30         
31         first.next = tem      # 将节点的首位连上
32         re.next = one
33         return res.next        # 返回结果
34         
 
 

 



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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值