zoukankan      html  css  js  c++  java
  • 【python-leetcode92-翻转链表】反转链表2

    问题描述:

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

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

    示例:

    输入: 1->2->3->4->5->NULL, m = 2, n = 4
    输出: 1->4->3->2->5->NULL
    class ListNode:
        def __init__(self,x):
            self.val=x
            self.next=None
    n1=ListNode(1)
    n2=ListNode(2)
    n3=ListNode(3)
    n4=ListNode(4)
    n5=ListNode(5)
    n1.next=n2;n2.next=n3;n3.next=n4;n4.next=n5
    
    def printListNode(head):
        while head != None:
            print(head.val)
            head=head.next
    #printListNode(n1)
    
    class Solution:
        def reverseBetween(self, head, m, n):
            if not head:
                return None
        
            cur, prev = head, None
            while m > 1:
                prev = cur
                cur = cur.next
                m, n = m - 1, n - 1
    
            p2, p1 = cur, prev
    
            while n:
                third = cur.next
                cur.next = prev
                prev = cur
                cur = third
                n -= 1
    
            if p1:
                p1.next = prev
            else:
                head = prev
            p2.next = cur
            return head
    s=Solution()
    s.reverseBetween(n1,2,4)
    printListNode(n1)

    具体过程:

    初始状态:

    进入第一个while循环之后:

    之后定义两个链接指针,p1,p2

    进入第二个while循环:

    第一步:

    第二步:

    第三步:

    此时退出循环。

    然后p1.next指向prev,p2.next指向cur 

  • 相关阅读:
    golang ---cron
    Maven私库安装与配置
    Java8新特性之重复注解(repeating annotations)浅析
    String split
    如何将xml转为python中的字典
    json字符串和dict互转
    为什么空格拷贝到linux 会变成两个
    python之socket编程
    ntpdate设置
    Nginx配置ssl证书
  • 原文地址:https://www.cnblogs.com/xiximayou/p/12368741.html
Copyright © 2011-2022 走看看