reorder-list
描述
Given a singly linked list L: L 0→L 1→…→L n-1→L n,
reorder it to: L 0→L n →L 1→L n-1→L 2→L 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){
return;
}
ListNode[] points=new ListNode[20000];
int i=0;
for(ListNode node=head;node!=null;node=node.next,i++){
points[i]=node;
}
int n=i;
for(i=0;i<n/2;i++){
points[i].next=points[n-i-1];
points[n-i-1].next=points[i+1];
if(i+1==(n/2)){
if(points[i+1].next!=null){
points[i+1].next=null;
}
}
}
}
}