排序链表

注意一些关于链表的常用操作

1、寻找链表的中间节点(快慢指针)

2、合并两个有序链表(哨兵节点的使用)

/**
 * 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 {
    // 自顶向下归并排序
    // 时间复杂度O(nlogn)
    // 空间复杂度O(logn)
    public ListNode sortList(ListNode head) {
        return sortList(head, null);
    }

    /**
     * 对子链表进行排序
     * 左闭右开,起点为head,tail为尾指针前的位置
     * @param head
     * @param tail
     * @return
     */
    public ListNode sortList(ListNode head, ListNode tail) {
        if (head == null) return head;
        if (head.next == tail) {
            head.next = null;   // 把子链表从原链表中断开
            return head;
        }

        // 寻找链表的中点(快慢指针)
        ListNode slow = head;
        ListNode fast = head;
        while (fast != tail && fast.next != tail) {
            slow = slow.next;
            fast = fast.next.next;
        }

        ListNode mid = slow;    // 找到链表的中间节点
        ListNode list1 = sortList(head, mid);
        ListNode list2 = sortList(mid, tail);
        ListNode sortedList = merge(list1, list2);

        return sortedList;
    }

    // 合并两个有序链表
    public ListNode merge(ListNode node1, ListNode node2) {
        // 哨兵节点
        ListNode dummyHead = new ListNode(0);
        ListNode tmp = dummyHead, tmp1= node1, tmp2 = node2;
        
        while (tmp1 != null && tmp2 != null) {
            if (tmp1.val <= tmp2.val) {
                tmp.next = tmp1;
                tmp1 = tmp1.next;
            } else {
                tmp.next = tmp2;
                tmp2 = tmp2.next;
            }
            tmp = tmp.next;
        }
        // 判断list1是否还有剩余
        if (tmp1 != null) {
            tmp.next = tmp1;
        }
        
        // 判断list2是否还有剩余
        if (tmp2 != null) {
            tmp.next = tmp2;
        }
        
        return dummyHead.next;
    }
}

 

posted @ 2021-11-04 13:28  Peterxiazhen  阅读(58)  评论(0编辑  收藏  举报