【LeetCode 中等题】66-重排链表

题目描述:给定一个单链表 LL0→L1→…→Ln-1→Ln ,将其重新排列后变为: L0→LnL1→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.

解法1。方法就是找到链表中间节点,断开成两段,把后半段逆转,然后再两个链表合并,互相改变next指针,如下

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

class Solution(object):
    def reorderList(self, head):
        """
        :type head: ListNode
        :rtype: void Do not return anything, modify head in-place instead.
        """
        if not head or not head.next:
            return

        # 找到中间节点,切断
        slow = head
        fast = slow.next
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        mid = slow.next
        slow.next = None
        
        # 逆转链表
        pre = None
        cur = mid
        while cur:
            tmp = cur.next
            cur.next = pre
            pre = cur
            cur = tmp
        
        # 前后两段链表合并
        head1 = head
        head2 = pre
        while head1 and head2:
            tmp = head2.next
            head2.next = head1.next
            head1.next = head2
            head1 = head1.next.next
            head2 = tmp

猜你喜欢

转载自blog.csdn.net/weixin_41011942/article/details/86254874
今日推荐