leetCode--reorder-list

来源:互联网 发布:提醒喝水的软件 编辑:程序博客网 时间:2024/06/18 14:09

Given a singly linked list LL 0L 1→…→L n-1L n,
reorder it to: L 0L n L 1L n-1L 2L n-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. * class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public void reorderList(ListNode head) {        if(head==null||head.next==null){            return;        }        ListNode slow=head;        ListNode fast=head.next;        //找到中点        while(fast!=null&&fast.next!=null){            slow=slow.next;            fast=fast.next.next;        }        ListNode after=slow.next;        slow.next=null;        ListNode pre=null;        //后半部分转置        while(after!=null){            ListNode tmp=after.next;            after.next=pre;            pre=after;            after=tmp;        }        //合并        ListNode first=head;        after=pre;        while(first!=null&&after!=null){            ListNode firstTmp=first.next;            ListNode afterTmp=after.next;            first.next=after;            first=firstTmp;            after.next=first;            after=afterTmp;        }    }}