Reorder List
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-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}.
思路: 利用slow和fast指针找到中间节点 slow指向 n/2 + 1个位置, fast指向尾部节点(奇数)或者null(偶数)
其次利用reverse,返回链表,即出入head之前,并变换head的指针
java代码:
- public void reorderList(ListNode head) {
- ListNode p = head;
- ListNode slow=head;
- ListNode fast = head;
- if(head==null || head.next==null) return;
- while(fast!=null && fast.next!=null) { //slow指针
- slow=slow.next;
- fast=fast.next.next;
- }
- fast=slow.next;
- slow.next=null;
- if(fast==null) return;
- p=fast.next;
- fast.next=null; //消除新链表的尾部
- while(p!=null){ //reverse
- ListNode tmp=p.next;
- p.next=fast;
- fast=p;
- p=tmp;
- }
- p=head;
- while(fast!=null) { //merge
- ListNode tmp=fast.next;
- fast.next=p.next;
- p.next=fast;
- p=p.next.next;
- fast=tmp;
- }
- // return head;
- }

浙公网安备 33010602011771号