public class Solution {
public ListNode reorderList(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode p = head;
ListNode q = head;
while(p.next!=null)
{
p=p.next;
if(p.next!=null)
p=p.next;
q=q.next;
}
ListNode k=q.next;
q.next=null;
ListNode head2 = new ListNode(-1);
while(k!=null){
p=k;
k=k.next;
p.next=null;
p.next=head2.next;
head2.next=p;
}
// while (head2!= null) {
// System.out.println(head2.val);
// head2 = head2.next;
// }
head2=head2.next;
q=head;
while(head2!=null){
p=head2;
head2=head2.next;
p.next=head.next;
head.next=p;
head=head.next.next;
}
return q;
}
public ListNode reorderList(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode p = head;
ListNode q = head;
while(p.next!=null)
{
p=p.next;
if(p.next!=null)
p=p.next;
q=q.next;
}
ListNode k=q.next;
q.next=null;
ListNode head2 = new ListNode(-1);
while(k!=null){
p=k;
k=k.next;
p.next=null;
p.next=head2.next;
head2.next=p;
}
// while (head2!= null) {
// System.out.println(head2.val);
// head2 = head2.next;
// }
head2=head2.next;
q=head;
while(head2!=null){
p=head2;
head2=head2.next;
p.next=head.next;
head.next=p;
head=head.next.next;
}
return q;
}
}
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}
.