重排链表
/**
* 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 =findmid(head);
ListNode head2=mid.next;
//断开链接后进行反转后半部
mid.next=null;
head2= reverse(head2);
//将两个链表按规律合并
while(head!=null && head2!=null){
ListNode next1 =head.next;
ListNode next2 =head2.next;
head.next=head2;
head =next1;
head2.next=head;
head2=next2;
}
}
//找到链表中心节点(力扣 876)
public ListNode findmid(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 reverse(ListNode head){
ListNode pre = null;
ListNode curr =head;
while(curr!=null){
ListNode next=curr.next;
curr.next=pre;
pre=curr;
curr=next;
}
return pre;
}
}
合并时的视频分析:
81a3dce2ef92af03a7666c5bb38d0f87