Reorder List(***)

来源:互联网 发布:python 金融数据接口 编辑:程序博客网 时间:2024/06/11 17:40

题目:
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;        }    }}
0 0
原创粉丝点击