/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public void reorderList(ListNode head) {
//1. 快慢指针找到中点
//2. 反转后半段链表, 使得前半段指向中间(正序), 后半段方向也指向中间(逆序)
//3. 分别从头结点和尾结点向中间遍历, 改变指针指向
if(head == null || head.next == null || head.next.next == null){
return;
}
//找中点
ListNode fast = head;
ListNode slow = head;
while(fast.next != null && fast.next.next != null){
fast = fast.next.next;
slow = slow.next;
}
if(fast.next != null){
slow = slow.next;
}
//反转链表
ListNode next = slow.next;
slow.next = null;
ListNode nextnext;
while(next!= null && next.next != null){
nextnext = next.next;
next.next = slow;
slow = next;
next = nextnext;
}
if(next != null){
next.next = slow;
}
//next指针指向尾结点
ListNode tail = next;
ListNode headi = head;
//改变指针指向
ListNode headTem;
ListNode tailTem;
while(true){
headTem = headi.next;
headi.next = tail;
headi = headTem;
if (headi == tail || headi == null) break;
tailTem = tail.next;
tail.next = headi;
tail = tailTem;
if (headi == tail || headi == null) break;
}
}
}
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public void reorderList(ListNode head) {
//1. 快慢指针找到中点
//2. 反转后半段链表, 使得前半段指向中间(正序), 后半段方向也指向中间(逆序)
//3. 分别从头结点和尾结点向中间遍历, 改变指针指向
if(head == null || head.next == null || head.next.next == null){
return;
}
//找中点
ListNode fast = head;
ListNode slow = head;
while(fast.next != null && fast.next.next != null){
fast = fast.next.next;
slow = slow.next;
}
if(fast.next != null){
slow = slow.next;
}
//反转链表
ListNode next = slow.next;
slow.next = null;
ListNode nextnext;
while(next!= null && next.next != null){
nextnext = next.next;
next.next = slow;
slow = next;
next = nextnext;
}
if(next != null){
next.next = slow;
}
//next指针指向尾结点
ListNode tail = next;
ListNode headi = head;
//改变指针指向
ListNode headTem;
ListNode tailTem;
while(true){
headTem = headi.next;
headi.next = tail;
headi = headTem;
if (headi == tail || headi == null) break;
tailTem = tail.next;
tail.next = headi;
tail = tailTem;
if (headi == tail || headi == null) break;
}
}
}