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.

思路:
1. 一个遍历指针 ite, 从头遍历
2. 一个尾部指针 tail,总是指向当前的尾节点
3. 当将尾节点,移动时,怎么找到这个节点的父节点了? – Map来存
4. 怎么判断遍历链表已经结束,也就是说不要在进行位置交换了? – ite.next = tail 或 ite= tail

public class Solution {
    public void reorderList(ListNode head) {
        if(head == null) return ;
        //从头到尾遍历链表
        ListNode ite = head;
        // 指向最后一个节点
        ListNode tail = head;
        // 存父节点
        HashMap<ListNode , ListNode > parent = new HashMap<>();
        while(tail.next != null) {
            ListNode tmp = tail;
            tail = tail.next;
            parent.put(tail , tmp);
        }
        while(true) {
        // 循环停止条件 奇数 : 第1个条件  偶数 : 第2个条件
            if(tail == ite || ite.next == tail) break;
            ListNode tmp = ite.next;
            ListNode tailParent = parent.get(tail);
            ite.next = tail;
            tail.next = tmp;
            ite = tmp;
            tailParent.next = null;
            tail = tailParent;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值