码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 143. 重排链表

时间:2020-07-12 14:37:49      阅读:45      评论:0      收藏:0      [点我收藏+]

标签:lin   lan   tco   efi   for   odi   list   turn   不能   

给定一个单链表?L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例?1:
给定链表 1->2->3->4, 重新排列为 1->4->2->3.
示例 2:
给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reorderList(self, head: ListNode) -> None:
        """
        Do not return anything, modify head in-place instead.
        """
        if head is None or head.next is None:
            return head
        slow = head
        fast = head.next 
        while fast is not None and fast.next is not None:
            slow = slow.next
            fast = fast.next.next
        
        cur = slow.next
        slow.next = None

        mid_head = None
        while cur:
            tmp = cur.next
            cur.next = mid_head
            mid_head = cur
            cur = tmp

        p1 = head
        p2 = mid_head
        while p1 is not None and p2 is not None:
            tmp1 = p1.next
            tmp2 = p2.next
            p1.next = p2
            p2.next = tmp1
            p1 = tmp1
            p2 = tmp2

LeetCode 143. 重排链表

标签:lin   lan   tco   efi   for   odi   list   turn   不能   

原文地址:https://www.cnblogs.com/sandy-t/p/13288121.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!