zoukankan      html  css  js  c++  java
  • LeetCode 143. 重排链表

    143. 重排链表

    Difficulty: 中等

    给定一个单链表 LL0→_L_1→…→_L_n-1→_L_n ,
    将其重新排列后变为: L0→_L_n→_L_1→_L_n-1→_L_2→_L_n-2→…

    你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

    示例 1:

    给定链表 1->2->3->4, 重新排列为 1->4->2->3.
    

    示例 2:

    给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
    

    Solution

    这题的难度应该不止中等,挺难的,操作有点复杂。参考题解:Java solution with 3 steps - LeetCode Discuss
    第二步

    第三步

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, val=0, next=None):
    #         self.val = val
    #         self.next = next
    class Solution:
        def reorderList(self, head: ListNode) -> None:
            """
            Do not return anything, modify head in-place instead.
            """
            if not head or not head.next: return 
            p1 = p2 = head
            # find the middle
            while p2.next and p2.next.next:
                p1 = p1.next
                p2 = p2.next.next
    ​
            # reverse the half after middle
            mid = p1
            pCurrent = p1.next
            while pCurrent.next:
                current = pCurrent.next
                pCurrent.next = current.next
                current.next = mid.next
                mid.next = current
     
            p1 = head
            p2 = mid.next
            while p1 != mid:
                mid.next = p2.next
                p2.next = p1.next
                p1.next = p2
                p1 = p2.next
                p2 = mid.next
    
  • 相关阅读:
    unix网络编程 初步了解TCP/IP协议
    unix网络编程 常见概念
    linux 环境变量
    linux c编程
    第二周学习笔记
    jmeter第一周学习笔记
    建造者模式
    原型设计模式
    抽象工厂模式
    工厂方法模式
  • 原文地址:https://www.cnblogs.com/swordspoet/p/14183454.html
Copyright © 2011-2022 走看看