[LeetCode] - Reorder List

本文详细阐述了如何通过快慢指针、链表反转及插入操作,实现链表的特定重组,具体步骤包括拆分、反转后半部分链表及有序插入。此算法适用于链表的综合练习,涉及链表常用操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-2→…

You must do this in-place without altering the nodes' values.

For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.


这道题像是一道链表的综合题,因为解题过程中需要用到很多链表的常用操作,比如快慢指针取中点,翻转链表等等。我觉得最好把其中的每个步骤都写成了一个函数,这样清楚明了。

具体的思路如下:

1. 拆分。用快慢指针找到链表的中点,然后将链表一分为二。初始条件应该设置为,slow=head, fast=head.next,然后进入while循环。这样出来的结果可以保证:(1)如果链表长度为偶数,则前半部分的长度和后半部分相等;(2)如果链表长度为奇数,则前半部分的长度比后半部分大1。这样的结果方便后面的insert。

2. 反转。对拆分之后的后半部分进行反转。链表反转的算法很常用了,就是加入一个fake,然后把head后面的每个node一个个的插入到fake和fake.next之间就可以了。

3. 插入。将反转之后的后半部分链表插入到前半部分之中。


代码如下:

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public void reorderList(ListNode head) {
        if(head==null || head.next==null) return;
        ListNode second = cut(head);
        second = reverse(second);
        insert(head, second);
        return;
    }
    
    public ListNode cut(ListNode head) {
        ListNode slow=head, fast=head.next;
        
        // odd->fast==null; even->fast.next==null
        // guarantee that the length of 1st half is equal or longer than the 2nd half
        while(fast!=null && fast.next!=null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode secHead = slow.next;
        slow.next = null;
        return secHead;
    }
    
    public ListNode reverse(ListNode head) {
        ListNode fake = new ListNode(-1);
        fake.next = head;
        ListNode cur = head.next;
        while(cur != null) {
            head.next = cur.next;
            cur.next = fake.next;
            fake.next = cur;
            cur = head.next;
        }
        return fake.next;
    }
    
    public void insert(ListNode first, ListNode second) {
        while(second != null) {
            ListNode temp = second.next;
            second.next = first.next;
            first.next = second;
            first = first.next.next;
            second = temp;
        }
        return;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值