您的位置:首页 > 编程语言 > Java开发

[leetcode]Reorder List

2015-10-18 21:31 609 查看
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);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 算法