148. Sort List

本文介绍了一种在O(n log n)时间内使用常数空间复杂度对链表进行排序的方法。通过递归地将链表分成越来越小的部分直至只剩两个节点,对这些小链表排序后再进行归并,最终实现整个链表的排序。

Sort a linked list in O(n log n) time using constant space complexity.

Example

Given 1->3->2->null, sort it to 1->2->3->null.

----------------------------------------------------------------------------------------

为了更加清晰的说明这个过程,我觉得换一个比较复杂的例子

Sorting a linked list in O(n log n) time using constant space complexity.

Example: Given 3 -> 2 -> 4-> 1 -> 5 -> NULL, sotr it to  1 -> 2-> 3-> 4-> 5-> NULL.

思路:如果链表只有两个节点,只要判断两个节点的大小,如果需要就呼唤位置组成新的链表即可;如果链表有四个节点,就分成两组,每组分别有两个节点,然后应用当只有两个节点的时候的情况,因为只有两个节点时,链表已经被排序,有四个节点的时候,最后会得到两个已经排序的链表,然后把他们在归并起来。

所以,将特殊情况发展到一般情况,就是先要把链表分成两部分,然后再把每一部分继续划分成更小的部分,直到变成仅有两个节点的情况,然后对他们进行排序,因为此时每个划分成最小的链表也至多两个节点,比较好排序,最后把排好的小链表一个一个合起来,组成原来的规模。

我们的任务:1,划分链表,2, 排序,3, 归并。

上代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* sortList(ListNode* head) {
        if (head == NULL || head->next == NULL) {
            return head;
        }
        ListNode* fast = head;
        ListNode* slow = head;
        while (fast->next != NULL && fast->next->next != NULL) {
            fast = fast->next->next;
            slow = slow->next;
        }
        fast = slow->next;
        slow->next = NULL;
        ListNode* l1 = sortList(head);
        ListNode* l2 = sortList(fast);
        head = mergeList(l1, l2);
        return head;
    }
    ListNode* mergeList(ListNode* l1, ListNode* l2) {
        if (l1 == NULL) return l2;
        if (l2 == NULL) return l1;
        ListNode* dummy = new ListNode(0);
        ListNode* temp = dummy;
        while (l1 != NULL && l2 != NULL) {
            if (l1->val < l2->val) {
                temp->next = l1;
                l1 = l1->next;
            } else {
                temp->next = l2;
                l2 = l2->next;
            }
            temp = temp->next;
        }
        if (l1 != NULL) temp->next = l1;
        if (l2 != NULL) temp->next = l2;
        return dummy->next;
    }
};


### Java 中 `Collections.sort` 的列表判空处理 在使用 `Collections.sort` 对列表进行排序之前,为了防止因操作空列表而引发异常(如 NullPointerException),可以先通过条件语句来判断列表是否为空或者长度是否为零。如果列表不为空,则执行排序逻辑;否则可以选择跳过排序或采取其他措施。 以下是实现这一功能的具体方法: #### 判空代码示例 ```java import java.util.*; public class SortExample { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); // 添加数据到列表 (可选) // list.add(5); // list.add(2); // list.add(8); // 判断列表是否为空 if (list != null && !list.isEmpty()) { Collections.sort(list); // 默认升序排序 System.out.println("Sorted List: " + list); } else { System.out.println("List is empty or null. No sorting performed."); } } } ``` 上述代码中,在调用 `Collections.sort` 方法前进行了两步验证: 1. 验证列表对象本身是否为 `null`。 2. 使用 `isEmpty()` 方法确认列表是否有任何元素[^1]。 只有当这两项检查都满足时才会继续执行排序过程,从而有效避免潜在错误的发生。 #### 自定义比较器情况下的判空处理 对于带有自定义比较器的情况,同样需要遵循类似的判空流程。例如按照价格降序排列商品信息时: ```java import java.util.*; class Product implements Comparable<Product>{ private String name; private double price; public Product(String name, double price){ this.name=name; this.price=price; } @Override public int compareTo(Product otherProduct){ return Double.compare(otherProduct.getPrice(),this.getPrice()); } public String getName() { return name; } public double getPrice(){ return price; } @Override public String toString(){ return "[Name="+name+",Price="+price+"]"; } } public class CustomSort{ public static void main(String []args){ List<Product> productList=new ArrayList<>(); // 可以在此处添加产品实例 if(productList!=null && !productList.isEmpty()){ Collections.sort(productList,new Comparator<Product>() { @Override public int compare(Product p1, Product p2) { return Double.compare(p2.getPrice(),p1.getPrice()); // 降序 } }); for(Product product : productList){ System.out.println(product.toString()); } }else{ System.out.println("The product list is either null or empty!"); } } } ``` 此段程序展示了如何安全地应用带参数版本的 `Collections.sort` 函数完成复杂类型的排序任务,并且包含了必要的前置检验步骤。 #### 总结说明 无论是在简单场景还是涉及定制化规则的情况下运用 `Collections.sort` 进行数组整理工作时,都应该养成良好习惯——即事先做好充分的数据状态评估准备动作,比如检测目标集合是否存在以及其内部成员数量状况等基本信息,以此保障整个算法运行期间不会因为意外因素而导致崩溃等问题发生。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值