两种思路
第一种:借助 外部容器 HashMap 但是对于这道题的时间复杂度过不了。
第二种:使用快慢指针找到链表中点,断开,翻转后半部分链表形成两个链表,最后交叉合并两个链表即可
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
import java.util.*;
public class Solution {
public HashMap<Integer,ListNode> map=new HashMap<>();
//逆序后半部分链表,然后拼接
public void reorderList(ListNode head) {
if(head==null||head.next==null||head.next.next==null){
return;
}
ListNode slow=head;
ListNode fast=head.next;
while(fast!=null&&fast.next!=null){
slow=slow.next;
fast=fast.next.next;
}
ListNode cur=slow;
//逆序后半部分链表
ListNode pre=null;
while(cur!=null){
ListNode next=cur.next;
cur.next=pre;
pre=cur;
cur=next;
}
ListNode index=head;
while(index!=null&&pre!=null){
ListNode indexNext=index.next;
ListNode preNext=pre.next;
index.next=pre;
pre.next=indexNext;
index=indexNext;
pre=preNext;
}
}
public void reorderListOld(ListNode head) {
if(head==null||head.next==null||head.next.next==null){
return;
}
ListNode index=head;
int length=0;
while(index!=null){
map.put(length++,index);
index=index.next;
}
length-=1;
for(int i=0;i<length;i++){
if(map.get(length-i)==null){
return;
}
map.get(i).next=map.get(length-i);
map.get(length-i).next=map.get(i+1);
}
}
}
京公网安备 11010502036488号