leetcode 143. Reorder List


Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-2→…

You may not modify the values in the list's nodes, only nodes itself may be changed.

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.



思路:1.快慢指针找中间节点。

          2.中间节点之后的链表构建第二个链表,注意和主链表断开。

          3.将链表2,按题意插入链表1。

特别注意边界情况,处理不好总是会出现空指针异常。

public void reorderList(ListNode head) {
        if(head==null||head.next==null) return;
       
        //快慢指针找到中间节点,再把后半节点逆序并断开,在插入前面那个链表
        ListNode slow=head,quick=head.next;
        while(quick!=null&&quick.next!=null){
            slow=slow.next;
            quick=quick.next.next;
        }
        ListNode s=slow.next;
        slow.next=null;
        
        //构建链表2,翻转链表,翻转后s为头结点,再和链表1合并
        ListNode post=s.next;
        s.next=null;
        while(post!=null){
            ListNode temp=post.next;
            post.next=s;       
            s=post;
            post=temp;
        }
        
        //合并两个链表
        ListNode node1=head;
        ListNode node2=s;
        while(node2!=null){
            ListNode temp=node2.next;
            node2.next=node1.next;
            node1.next=node2;
            node1=node2.next;            
            node2=temp;
        }
    }

猜你喜欢

转载自blog.csdn.net/yaoct/article/details/80413533