[leetcode]Reorder List

来源:互联网 发布:淘宝助手 mac 编辑:程序博客网 时间:2024/05/29 12:02
public class Solution {
    public static void reorderList(ListNode head) {
        if(head==null||head.next==null)
            return ;
        ListNode tmp,revhead=head,pre,cur=head,next;
        int len=0,lp;
        while(cur!=null){
            cur=cur.next;
            len++;
        }
        lp=(len+1)/2;
        cur=head;
        while(lp-->1){
            cur=cur.next;
        }
        revhead=cur.next;
        cur.next=null;
        cur=revhead.next;
        pre=revhead;
        while(cur!=null){
            next=cur.next;
            cur.next=pre;
            pre=cur;
            cur=next;
        }
        revhead.next=null;
        //反转之后的链表头
        revhead=pre;
        cur=head;
        while(revhead!=null){
           next=cur.next;
           tmp=revhead.next;
           cur.next=revhead;
           revhead.next=next;
           cur=next;
           revhead=tmp;
        }
        return ;
    }
    public static void main(String[] args) {
    ListNode t1=new ListNode(1);
ListNode t2=new ListNode(2);
ListNode t3=new ListNode(3);
t1.next=t2;
t2.next=t3;
reorderList(t1);
}
}
0 0
原创粉丝点击