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}
.
/** * 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) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if (head==null || head.next==null){ return; } ListNode p1 = head; ListNode temp = null; ListNode p2 = null,p=null; int len=0,i=0; //求长度 while (p1!=null) { p1 = p1.next; len++; } //把p移动到一半位置 p = head; while (p !=null && i<len/2-1) { p = p.next; i++; } //把后半部分逆序排列 p1 = p.next.next; p2 = p.next; p2.next = null; while (p1 !=null) { temp = p1.next; p1.next = p2; p2 = p1; p1 = temp; } p.next = p2; p = p.next; //从head重新组织 p1 = head; ListNode p1n = null,pn=null; ListNode pstop=p; while(p.next!=null){ pn = p.next; p1n = p1.next; p.next = p1.next; p1.next = p; p = pn; p1 = p1n; if (p1.next==pstop){ p1.next = p; break; } } } }