
题解1:类似于暴力破解
通过数组存储链表元素
利用数组的指针特性重新建立需要的链表
解法一:暴力破解
/**
* 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 void reorderList(ListNode head) {
if(head == null) return
LinkedList<ListNode> list = new LinkedList<>()
ListNode temp = head
while(temp!=null){
list.add(head)
temp=temp.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
}
}
题解2
将链表分成两个链表,并将后半部分翻转,接着连接两个链表
解法二:拆分链表
/**
* 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 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 mid = slow.next
slow.next=null
ListNode newHead= reverse(mid)
while(newHead!=null){
ListNode temp =newHead.next
newHead.next=head.next
head.next=newHead
head=newHead.next
newHead=temp
}
}
public ListNode reverse(ListNode head){
if(head == null)
return head
ListNode pre=null
ListNode temp=null
while(head!=null){
temp=head.next
head.next=pre
pre=head
head=temp
}
return pre
}
}