【重排链表】双指针+反转链表+合并链表

发布时间 2023-12-19 12:50:06作者: 沙汀鱼

leetcode 143. 重排链表

题意:
给定一个单链表 L 的头节点 head ,单链表 L 表示为:
L0 → L1 → … → Ln - 1 → Ln

请将其重新排列后变为:
L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …

不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

题解:
可以发现重新排列的链表,是原链表前半段和反转后的后半段交替

  1. 使用快慢指针找到链表的中间节点,将链表从中间节点断开,保证链表前半段长度不小于后半段
  2. 将后半段的链表反转
  3. 重新合并两个链表
点击查看代码
/**
 * 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 dummy = new ListNode(0, head);
        ListNode slow = dummy, fast = dummy;
        while(fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode fir = head, sec = slow.next;
        sec = reverse(sec);
        while(sec != null) {
            ListNode nextSec = sec.next;
            sec.next = fir.next;
            fir.next = sec;
            fir = sec.next;
            sec = nextSec;
        }
        fir.next = null;
    }

    public ListNode reverse(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode res = reverse(head.next);
        head.next.next = head;
        head.next = null;
        return res;
    }
}