给定一个单链表 L 的头节点 head ,单链表 L 表示为:
L0 → L1 → … → Ln - 1 → Ln
请将其重新排列后变为:
L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
输入:head = [1,2,3,4]
输出:[1,4,2,3]
示例 2:
输入:head = [1,2,3,4,5]
输出:[1,5,2,4,3]
提示:
链表的长度范围为 [1, 5 * 104]
1 <= node.val <= 1000
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public void reorderList(ListNode head) {
ListNode pre = new ListNode(0);
ListNode fast = pre, slow = pre;
pre.next = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
}
ListNode next = slow.next;
slow.next = null; //断开前半部分
ListNode reverse_node = reverse(next);
ListNode cur = pre.next;
while(reverse_node != null){ //穿插
ListNode reverse_next = reverse_node.next;
ListNode cur_next = cur.next;
cur.next = reverse_node;
reverse_node.next = cur_next;
cur = cur_next;
reverse_node = reverse_next;
}
}
//反转链表操作
public ListNode reverse(ListNode node){
ListNode pre = null;
while(node != null){
ListNode next = node.next;
node.next = pre;
pre = node;
node = next;
}
return pre;
}
}