Loading

[链表]重排链表

# 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: Optional[ListNode]) -> None:
        """
        Do not return anything, modify head in-place instead.
        """

        fast,slow = head,head

        while fast.next and fast.next.next:
            fast = fast.next.next
            slow = slow.next

        cur = slow.next
        slow.next = None

        dummy = ListNode(-1)

        while cur:
            t = cur
            cur = cur.next
            t.next = dummy.next
            dummy.next = t


        cur1,cur2 = head,dummy.next
        dummy = ListNode(-1)
        tail = dummy
        while cur1 and cur2:
            
            tail.next = cur1
            cur1 = cur1.next
            tail = tail.next
            tail.next = None

            tail.next = cur2
            cur2 = cur2.next
            tail = tail.next
            tail.next = None

        if cur1:
            tail.next = cur1
        if cur2:
            tail.next = cur2

        return dummy.next


posted @ 2024-09-27 10:03  Duancf  阅读(21)  评论(0)    收藏  举报