2017.10.23
首先遍历链表,建立两个队列,一个存放前一半一个存放后一半。
然后再遍历这两个队列,建立新的连接关系,重排链表。
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The head of linked list.
* @return: void
*/
public void reorderList(ListNode head){
if(head == null || head.next == null){
return ;
}
LinkedList<ListNode> queue1 = new LinkedList<ListNode>();
LinkedList<ListNode> queue2 = new LinkedList<ListNode>();
//所有的节点均先入栈
while(head != null){
queue1.addFirst(head);
head = head.next;
}
int i = queue1.size()/2;
while(i > 0){
queue2.addLast(queue1.pollFirst());
i--;
}
head = queue1.pollLast();
head.next = null;
ListNode bt = head;
while(!queue1.isEmpty()){
queue2.peekFirst().next = queue1.peekLast();
queue1.peekLast().next = bt.next;
bt.next = queue2.pollFirst();
bt = queue1.pollLast();
}
while(!queue2.isEmpty()){
queue2.peekFirst().next = bt.next;
bt.next = queue2.pollFirst();
}
}
}