reorder list

来源:互联网 发布:asp源码什么 编辑:程序博客网 时间:2024/06/05 07:03

Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-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}.

public class Solution {    public ListNode reverse(ListNode head){        ListNode pre=null;        ListNode ruNode=head;        ListNode result=null;        while(ruNode!=null){            ListNode nextNode=ruNode.next;            if(nextNode==null){                result=ruNode;            }            ruNode.next=pre;            pre=ruNode;            ruNode=nextNode;        }        return result;    }    public void merge(ListNode l1,ListNode l2){        while(l1!=null){            ListNode l2next=l2.next;            ListNode l1next=l1.next;                        l1.next=l2;            if (l1next== null)          break;//l2比l1长一个单位,l1到最后一个节点的时候,就可以退出merge过程了            l2.next=l1next;            l1=l1next;            l2=l2next;        }    }    public void reorderList(ListNode head) {        if(head==null||head.next==null) return;        ListNode slow=head;        ListNode fast=head;        ListNode pre=null;        while(fast!=null&&fast.next!=null){            pre=slow;            slow=slow.next;            fast=fast.next.next;        }        pre.next=null;        ListNode result2=reverse(slow);        merge(head,result2);    }}


0 0
原创粉丝点击