题解 | #重排链表#
重排链表
https://www.nowcoder.com/practice/3d281dc0b3704347846a110bf561ef6b
import java.util.*;
/**
* 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:先用单双指针把找到中位数点,然后将后面的链表反向,再交叉两个链表,得到结果
//若数量低于3没有变化
if(head==null||head.next==null||head.next.next==null)
return;
//移动指针1.2
ListNode l1= head;
ListNode l2= head;
ListNode temp=new ListNode(0);
//1.先用单双指针把找到中位数点
int count=0;
while(l1.next!=null)
{
l1=l1.next;
count++;
if(count==2)
{
count=0;
l2=l2.next;
}
}
temp.next=l2.next;
l2.next=null;
l2=temp.next;
//l2的位置后半链表的起点;
//2.将l2链表反置
//第二个链表的为0的头指针
ListNode head2=new ListNode(0);
while(l2!=null)
{
temp.next=l2.next;
l2.next=head2.next;
head2.next=l2;
l2=temp.next;
}
//注意head2是一个无意义的对象,只是为了链表转置方便
//3.再交叉两个链表
l1=head;
l2=head2.next;
ListNode temp1=new ListNode(0);
ListNode temp2=new ListNode(0);
while(l2!=null)
{
temp1.next=l1.next;
l1.next=l2;
temp2.next=l2.next;
l2.next=temp1.next;
l1=temp1.next;
l2=temp2.next;
}
}
}
查看7道真题和解析