Leetcode Sort List

本文介绍了一种使用归并排序算法对链表进行排序的方法。通过遍历链表,将其节点存储于数组中,再利用归并排序的思想对数组中的链表节点进行排序,最后连接成有序链表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:将链表排序。

思路:使用归并排序。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    vector<ListNode*> mylist;
    ListNode* sortList(ListNode* head) {
        if(head == NULL) return head;
        ListNode* next = head;
        while(next) {
            mylist.push_back(next);
            next = next->next;
        }
        
        next = mysort(0, mylist.size() - 1);
        
        return next;
    }
    
    ListNode* mysort(int low, int high) {
        if(low == high) {
            mylist[low]->next = NULL;
            return mylist[low];
        }
        
        int mid = low + (high - low) / 2;
        
        ListNode* temp1 = mysort(low, mid); //if(temp1) cout << temp1->val << endl;
        ListNode* temp2 = mysort(mid + 1, high); //if(temp2) cout << temp2->val << endl;
        cout << endl;
        
        ListNode* myhead = new ListNode(0);
        ListNode* next = myhead;
        
        while(temp1 || temp2) {
            ListNode* tempnext = NULL;
            if(temp1 && temp2) {
                if(temp1->val < temp2->val) {
                    tempnext = temp1;
                    temp1 = temp1->next;
                    
                }
                else {
                    tempnext = temp2;
                    temp2 = temp2->next;
                }
                next->next = tempnext;
                next = tempnext;
                continue;
            }
            if(temp1 && !temp2) {
                tempnext = temp1;
                temp1 = temp1->next;
                next->next = tempnext;
                next = tempnext;
                continue;
            }
            if(!temp1 && temp2) {
                tempnext = temp2;
                temp2 = temp2->next;
                next->next = tempnext;
                next = tempnext;
                continue;
            }
        }
        //next->next = NULL;
        //show the list
        /*
        ListNode* testnext = myhead;
        while(testnext) {
            cout << testnext->val << " ";
            testnext = testnext->next;
        }
        cout << endl;
        */
        next = myhead->next;
        delete myhead;
        
        return next;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值