牛客BM12. 单链表的排序

Description:

题目大意:排序单链表元素

解题思路:方法一:(更优)

算法标签:sort 排序

  1. 存储链表元素
  2. 直接排序
  3. 赋值原来的链表

代码:

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */

class Solution {
public:
    ListNode* sortInList(ListNode* head) {
        vector<int>number;
        ListNode* dummyhead = head;
        while(dummyhead != NULL) {
            number.push_back(dummyhead -> val);
            dummyhead = dummyhead -> next;
        }
        sort(number.begin(),number.end());
        
        dummyhead = head;
        for(int i = 0;i < number.size();i++) {
            dummyhead -> val = number[i];
            dummyhead = dummyhead -> next;
        }
        
        return head;
    }
};

解题思路:方法二:

算法标签:归并排序

代码:

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */

class Solution {
public:
    ListNode* sortInList(ListNode* head) {
        if((head == NULL) || (head -> next == NULL))
            return head;
        // 使用快慢指针寻找链表的中点
        ListNode* fast = head -> next;
        ListNode* slow = head;
        while(fast != NULL && fast -> next != NULL) {
            slow = slow -> next;
            fast = fast -> next -> next;
        }
        
        // 断开链表
        ListNode* mid = slow -> next;
        slow -> next = NULL;
        
        // 递归左右两边进行排序
        ListNode* left = sortInList(head);
        ListNode* right = sortInList(mid);
        
        // 创建新链表
        ListNode* temp = new ListNode(0);
        ListNode* res = temp;
        // 合并 left 和 right 两个链表
        while(left != NULL && right != NULL) {
            if(left -> val <= right -> val) {
                temp -> next = left;
                left = left -> next;
            }
            else {
                temp -> next = right;
                right = right -> next;
            }
            temp = temp -> next;
        }
        
        if(left != NULL) {
            temp -> next = left;
        }
        else
            temp -> next = right;
        
        return res -> next;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值