Q143 重排链表
给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
给定链表 1->2->3->4, 重新排列为 1->4->2->3.
示例 2:
给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public void reorderList(ListNode head) {
if (head == null || head.next == null || head.next.next == null)
return;
ListNode node1 = head;
ListNode node2 = head;
while (node2.next != null && node2.next.next != null) {
node2 = node2.next.next;
node1 = node1.next;
}
ListNode tail = node2.next == null ? node2 : node2.next;
node2 = node1.next;
node1.next = null;
node1 = node2;
node2 = node1.next;
node1.next = null;
while (node2 != null) {
ListNode node3 = node2.next;
node2.next = node1;
node1 = node2;
node2 = node3;
}
node1 = head;
node2 = tail;
while (node2 != null) {
ListNode temp = node2;
node2 = node2.next;
temp.next = node1.next;
node1.next = temp;
node1 = temp.next;
}
}
}