zoukankan      html  css  js  c++  java
  • LeetCode:92. 反转链表 II

    1、题目描述

    反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。

    说明:
    1 ≤ m ≤ n ≤ 链表长度。

    示例:

    输入: 1->2->3->4->5->NULL, m = 2, n = 4
    输出: 1->4->3->2->5->NULL
    

    2、题解

    2.1、解法一

    class Solution:
        def reverseBetween(self, head, m, n):
            """
            :type head: ListNode
            :type m: int
            :type n: int
            :rtype: ListNode
            """
            # 反转
            count = 0
            node = head
            stack = []
            left = head
            right = None
    
            ret = []
            while node:
                count += 1
                if count <m:
                    left = node
                    ret.append(node.val)
                elif count >= m and count <=n:
                    stack.append(node)
                elif count >n:
                    right = node
                    while len(stack):
                        tmp = stack.pop()
                        ret.append(tmp.val)
                        left.next = tmp
                        left = tmp
                    left.next = right
                    ret.append(right.val)
    
                node = node.next
            else:
                while len(stack):
                    ret.append(stack.pop().val)
            return ret
    

      

  • 相关阅读:
    第07组 Alpha冲刺 (2/6)
    第07组Alpha冲刺(1/6)
    第四次作业
    面试题练习
    SpringMVC访问静态资源
    MyBatis基础
    Spring注解和jdk注解
    自动代理生成器
    aspect xml
    Spring-案例
  • 原文地址:https://www.cnblogs.com/bad-robot/p/10065444.html
Copyright © 2011-2022 走看看