zoukankan      html  css  js  c++  java
  • [leedcode 143] Reorder List

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

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public void reorderList(ListNode head) {
            //本题注意将slow和fast划分成两个链表时,注意最后一个节点的处理,下面的算法是两个表公用了一个尾节点
            //也可以把两个尾节点都置null
            //本题需要针对节点个数的奇偶分别进行考虑,举例子!!
            if(head==null||head.next==null||head.next.next==null) return;
            ListNode fast=head;
            ListNode slow=head;
            while(fast!=null&&fast.next!=null){
                fast=fast.next.next;
                slow=slow.next;
            }
            fast=head;
            ListNode head2=reverse(slow);//reverse slow list
            ListNode head2last=head2; //merge slow and head
            while(fast!=head2last&&fast.next!=head2last){
                head2last=head2.next;
                head2.next=fast.next;
                fast.next=head2;
                fast=head2.next;
                head2=head2last;
            }
            return;
        }
        public ListNode reverse(ListNode node){
            ListNode pre=node;
            ListNode last=null;
            while(node!=null){
                pre=node.next;
                node.next=last;
                last=node;
                node=pre;
            }
            return last;
        }
    }
  • 相关阅读:
    BZOJ1443 [JSOI2009]游戏Game
    BZOJ4950 [Wf2017]Mission Improbable
    假期编程
    假期编程
    假期编程
    假期编程
    假期编程练习-求和
    假期编程练习——一个数的n次幂取余
    假期编程练习———十进制转二进制
    小球抛物线运动
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4678935.html
Copyright © 2011-2022 走看看