Leetcode143. 重排链表

259 阅读1分钟

这道题采用反转链表那道工具题+快慢指针。最后一步的合并链表,只要理清楚每一轮的迭代关系,也很好解
时间复杂度:O(n) 空间复杂度: O(1)

image.png

/**
 * 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 slow = new ListNode(-1);
        ListNode fast = slow;
        slow.next = head;
        while(fast!=null && fast.next!=null){
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode newHead = reverListLoop(slow.next);
        slow.next = null;

        //合并链表
        ListNode pre = new ListNode(-1);
        pre.next = head;
        ListNode cur = head;
        ListNode newCur = newHead;
        while(cur!=null && newCur!=null){
            cur = cur.next;
            newCur = newCur.next;
            head.next = newHead;
            newHead.next = cur;
            head = cur;
            newHead = newCur;
        }
        pre = pre.next;
    }

    // 迭代方式反转链表
    public ListNode reverListLoop(ListNode root){
        ListNode pre = new ListNode(-1);
        ListNode cur = root;
        while(cur!=null){
            cur = cur.next;
            root.next = pre.next;
            pre.next = root;
            root = cur;
        }
        return pre.next;
    }
}