[leetcode]Reorder List

本文介绍了一种解决LeetCode上ReorderList问题的方法,该方法通过快慢指针找到链表中点,将链表后半部分逆序后重新组合。此解法的空间复杂度为O(1),时间复杂度为O(n)。

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

新博文地址:[leetcode]Reorder List

Reorder List

Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-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}.

 

算法思路:

设置快慢指针将前半段与后半段分开,然后将后半段逆序,再逐个插入前半段,时间复杂度O(n),空间复杂度不定

思路1:

后半段的逆序,设置三指针,在原list基础上逆序,空间复杂度O(1)

后面还有一些题会用这个思路,这里就不实现了。

 

代码如下:

 

public class Solution {
    public void reorderList(ListNode head) {
        if(head == null || head.next == null) return ;
        ListNode hhead = new ListNode(0);
        hhead.next = head;
        ListNode fast = hhead;
        ListNode slow = hhead;
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
        }
        ListNode stackPart = slow.next;
        slow.next = null;
        Stack<ListNode> stack = new Stack<ListNode>();
        while(stackPart != null){
            stack.push(stackPart);
            stackPart = stackPart.next;
        }
        ListNode insert = head;
        while(!stack.isEmpty()){
            ListNode tem = stack.pop();
            tem.next = insert.next;
            insert.next = tem;
            insert = tem.next;
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值