143. 重排链表

题目来源

143. 重排链表

题目描述

143. 重排链表_第1张图片

题目解析

一般解法

  • 快慢指针找到中间:
    • 奇数个:slow指向最中间的那一个。然后取得 second = slow.next, slow.next = null, first = head
    • 偶数个:slow指向中间偏右的那一个。然后second = slow.next。slow.next = null, first = head
  • second链表反转
  • 把second塞入first间隙
/**
 * 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) {
        if (head == null || head.next == null){
            return;
        }
        // 快慢指针找中间
        ListNode fast = head, slow = head;
        while (fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
        }

        ListNode first = head;
        ListNode second = slow.next;
        slow.next = null;

        // 反转第二个链表
        second = reverse(second);

        // 链表塞入
        while (second != null && first != null){
            ListNode t = first.next;
            ListNode s = second.next;
            first.next = second;
            second.next = t;
            second = s;
            first = first.next.next; // 小心
        }

    }

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

        while (cur != null){
            ListNode t = cur.next;
            cur.next = pre;
            pre = cur;
            cur = t;
        }

        return pre;
    }
}

在这里插入图片描述

链表转数组,然后前后指针构建新链表

/**
 * 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) {
        if (head == null || head.next == null){
            return;
        }

        ArrayList<ListNode> list = new ArrayList<>();
        while (head != null){
            list.add(head);
            head = head.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;
    }

}

在这里插入图片描述

递归方法待研究

你可能感兴趣的:(算法与数据结构,#,链表)