示例 1:
给定链表 1->2->3->4, 重新排列为 1->4->2->3.示例 2:
给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.class Solution {
public ListNode reorderList(ListNode head) {
if(head == null || head.next == null || head.next.next == null) return head;
ListNode low = head;
ListNode high = head;
ListNode headPointer = head;
Stack<ListNode> stack = new Stack<>();
//快慢指针寻找中点
while( high != null && high.next != null ){
low = low.next;
high = high.next.next;
}
//切分链表
ListNode seconed = low.next;
low.next = null;
//用栈保存后一段链表,主要是翻转链表
while(seconed != null){
stack.push(seconed);
seconed = seconed.next;
}
//弹栈 逐个插入第一个链表
while(!stack.isEmpty()){
ListNode insertNode = stack.pop();
insertNode.next = headPointer.next;
headPointer.next = insertNode;
headPointer = headPointer.next.next;
}
return head;
}
}