[Leetcode] 92. Reverse Linked List II 指定翻转m~n的链表

92. Reverse Linked List II (题目链接

Medium

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

思路:

关键变量:

pre_node  = ListNode() 表示需要翻转的链表的其实节点的前一个节点,也就是都(m-1)个节点

front_node = None 表示第m的节点

post_node = None 表示第n+1个节点

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
        if m == n:
            return head
        cur, cur_next = head, head.next
        pre_node, front, post_node = ListNode(), None, None
        cnt = 1
        flag = False
        while cnt < n:
            if cnt == m:
                front = cur
                cur_next = cur.next
                while True:
                    if cnt + 1 == n:
                        post_node = cur_next.next
                        cur_next.next = cur
                        flag = True
                        break
                    else:
                        cur_next_next = cur_next.next
                        cur_next.next = cur
                        cur = cur_next
                        cur_next = cur_next_next
                        cnt += 1
                if flag:
                    break
            else:
                cnt += 1
                pre_node = cur
                cur = cur.next
        
        pre_node.next = cur_next
        front.next = post_node
        
        if m == 1:
            return cur_next
        else:
            return head
            

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值