• 【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 

  • 相关阅读:
    JS 数组
    JS 模拟彩票
    C++ 动态内存
    计算机网络--OSI七层模型
    C++ 异常处理
    C++ 文件和流
    数据库学习教程网站
    数据结构--哈夫曼树
    数据结构--红黑树
    数据结构--伸展树
  • 原文地址:https://www.cnblogs.com/xiximayou/p/12368741.html
Copyright © 2020-2023  润新知