题目:
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}.
思路:遍历得到链表的长度,遍历得到链表的中间位置后的结点,将中间位置后的链表逆序,然后再将逆序的结点依次间隔插入前半段链表中。
java具体实现:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public void reorderList(ListNode head) {
if(head == null){
return ;
}
int len = 0;
ListNode p = head;
ListNode end = head;
while(p != null){
p = p.next;
len++;
}
if(len % 2 == 1){
len = len + 1;
}
int mid = len/2;
int i = 0;
ListNode start = head;
while(i < mid){
start = start.next;
if(i == mid-2){
end = start;
}
i++;
}
end.next = null;
start = rev(start);
p = head;
while(start!=null){
ListNode temp = start;
start = start.next;
temp.next = p.next;
p.next = temp;
p = p.next.next;
}
}
public ListNode rev(ListNode head){
if(head == null){
return head;
}
ListNode p1 = head;
if(p1.next == null){
return head;
}
ListNode p2 = p1.next;
if(p2.next == null){
p2.next = p1;
p1.next = null;
head = p2;
}else{
ListNode p3 = p2.next;
p1.next = null;
while(p3!= null){
p2.next = p1;
p1 = p2;
p2 = p3;
p3 = p3.next;
}
p2.next = p1;
head = p2;
}
return head;
}
}