注意以下几点
1. 传入为空
由于题目要求比较宽泛,所以采用以下两种方式解答
1. 用空间降低复杂度,使用list存储,借助数组编号寻址,重组链表
/**
* 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) {
if(head == null){
return;
}
List<ListNode> list = new ArrayList<ListNode>();
while (head !=null ){
list.add(head);
head = head.next;
}
ListNode a = new ListNode(-1);
for(int i=0; i<=(list.size()-1)/2; i++){
int j = list.size() - 1- i;
a.next = list.get(i);
a = a.next;
a.next = list.get(j);
a = a.next;
a.next=null;
}
}
}
2. 纯链表操作,链表分成前后两段,后段倒序,两段链表进行merge
public void reorderList(ListNode head){
if(head == null){
return;
}
ListNode t = new ListNode(-1);
t.next = head;
ListNode slow = t;
ListNode fast = t;
while (fast != null){
slow = slow.next;
fast = fast.next;
if(fast !=null){
fast = fast.next;
}
}
ListNode tailHead = null;
ListNode tailP1 = slow.next;
if(tailP1 == null){
return;
}
slow.next = null;
if(tailP1.next != null){
ListNode tailP2 = tailP1.next;
tailP1.next=null;
if(tailP2.next != null){
ListNode tailP3 = tailP2.next;
while (tailP3 != null){
tailP2.next = tailP1;
tailP2 = tailP3;
tailP1 = tailP2;
tailP3 = tailP3.next;
}
tailP2.next = tailP1;
}else {
tailP2.next = tailP1;
}
tailHead = tailP2;
}else {
tailHead = tailP1;
};
ListNode a = new ListNode(-1);
while (head !=null && tailHead != null){
a.next = head;
head = head.next;
a.next.next = tailHead;
tailHead = tailHead.next;
a=a.next.next;
}
if(head!=null){
a.next = head;
}
if(tailHead != null){
a.next = tailHead;
}
System.out.println();
}