美文网首页
143. Reorder List

143. Reorder List

作者: weiyongzhiaaa | 来源:发表于2020-04-15 11:25 被阅读0次

    Example 1:

    Given 1->2->3->4, reorder it to 1->4->2->3.
    Example 2:

    Given 1->2->3->4->5, reorder it to 1->5->2->4->3.

    idea:
    (自己想的)
    iteration: hashmap存每个node的previous node。两个指针一个从前一个从最后开始,不断把前指针的next设置成后一个指针对应的元素,直到head == tail or head.next == tail

    code:

            while (head != tail && head.next != tail) {
                ListNode storeHead = head.next;
                head.next = tail;
                ListNode storeTail = map.get(tail);
                storeTail.next = null;
                tail.next = storeHead;
                
                head = storeHead;
                tail = storeTail;
            }
    

    相关文章

      网友评论

          本文标题:143. Reorder List

          本文链接:https://www.haomeiwen.com/subject/ennqvhtx.html