LeetCode 148. Sort List

Tag:List

Difficulty:Medium

Problem

链表排序

给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表

Solution

解法一:用排序算法对链表排序,比如147. Insertion Sort List

解法二: 转换成数组排序问题。放在数组 -> 排序 -> 串起来

public ListNode sortList(ListNode head) {
    List list = new ArrayList<>();
    while (head != null) {
        list.add(head.val);
        head = head.next;
    }
    list.sort(((o1, o2) -> o1 - o2));
    ListNode res = new ListNode(-1);
    ListNode p = res;
    for (int i = 0; i < list.size(); i++) {
        p.next = new ListNode(list.get(i));
        p = p.next;
    }
    p.next = null;
    return res.next;
}

你可能感兴趣的:(LeetCode,leetcode,list,数据结构)