/**
* 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 mid = middleNode(head);
ListNode tail=reverseList(mid.next);
ListNode curr = head;
while (tail!=null&&curr!=null){
ListNode next = curr.next;
ListNode tailNext = tail.next;
curr.next=tail;
curr.next.next=next;
tail=tailNext;
curr=next;
}
curr.next=tail;
}
public ListNode middleNode(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
}
2、利用线性表存储该链表,然后利用线性表可以下标访问的特点,直接按顺序访问指定元素,重建该链表即可。
class Solution {
public void reorderList(ListNode head) {
if (head == null) {
return;
}
List<ListNode> list = new ArrayList<ListNode>();
ListNode node = head;
while (node != null) {
list.add(node);
node = node.next;
}
int i = 0, j = list.size() - 1;
while (i < j) {
list.get(i).next = list.get(j);
i++;
if (i == j) {
break;
}
list.get(j).next = list.get(i);
j--;
}
list.get(i).next = null;
}
}
class Solution {
public void reorderList(ListNode head) {
ListNode left=new ListNode(0,head);
ListNode right=new ListNode(0,head);
DFS(left,right);//递归
}
public ListNode DFS(ListNode left,ListNode right){
if(right==null){
return left;//left指向为止末尾
}
if(right.next==null){
return left.next;//left指向为止末尾
}
//快慢指针,right到了末尾,返回node就是未拼接的最后一个节点
ListNode node=DFS(left.next,right.next.next);
//2->3->4 === 4->2->3
if(node.next==null){
return null;//为空
}
ListNode temp=left.next;
left.next=node.next;
node.next=node.next.next;
left.next.next=temp;//交换
return node;
}
}