lintcode--99. 重排链表

本文介绍了一种链表重组算法,该算法将链表分为两部分,后半部分逆序后,交替插入到前半部分之间,实现原地操作且不改变节点值。适用于1->2->3->4->null变为1->4->2->3->null的情况。

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

描述

给定一个单链表L: L0→L1→…→Ln-1→Ln,

重新排列后为:L0→Ln→L1→Ln-1→L2→Ln-2→…

必须在不改变节点值的情况下进行原地操作。

样例

给出链表 1->2->3->4->null,重新排列后为1->4->2->3->null

挑战

Can you do this in-place without altering the nodes’ values?

代码

1.将链表拆成两半。
2.将后一半链表逆序。
3.再把逆序后的链表一个一个地每隔一个插入前一半链表中。

/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param head: The head of linked list.
     * @return: nothing
     */
    public void reorderList(ListNode head) {
        // write your code here
        if(head==null||head.next==null){
            return;
        }
        ListNode slow=head,fast=head;
        while(fast!=null&&fast.next!=null){
            slow=slow.next;
            fast=fast.next.next;
        }
        ListNode q=slow.next;
        slow.next=null;
        slow=q;
        //逆序
        ListNode pre=null;
        while(slow!=null){
            ListNode next=slow.next;
            slow.next=pre;
            pre=slow;
            slow=next;
        }
        //一个个插入左链表
        ListNode cur=head,reserve=pre;
        while(reserve!=null){
            ListNode p=reserve;
            reserve=reserve.next;
            p.next=cur.next;
            cur.next=p;
            cur=p.next;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值