148. 排序链表

我希望我刷题的目的是提升自己,不是为了ac

这个题目没有写出来,因为不知道链表归并排序的好处

我于是尝试了如何使用map,自动排序嘛

学会了

插入insert(pair<int,int>(x,y))

以及如何弹出第一个,以为是红黑树底层,遍历需要注意

map是一个不重复key值,所以我没通过:

贴一下错误代码:

查看代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* sortList(ListNode* head) {
        map<int,ListNode*>m;

        ListNode* temp = head;
        ListNode* temp_1;
        while(temp!=nullptr){
            auto index = temp->val;
            temp_1 = temp;
            temp = temp->next;
            temp_1->next = nullptr;
          //插入,因为map不熟练,所以挺多变量
            m.insert(pair<int,ListNode*>(index,temp_1));
            for(auto iter = m.begin();iter != m.end();iter++){
                cout<<iter->first;
        }
        }  
        for(auto iter = m.begin();iter != m.end();iter++){
                cout<<iter->second->val;  
        } 
        ListNode* h = new ListNode();
        temp = h;
       
        while(!m.empty()){
          //另一种遍历方法
            auto iter = m.begin();
            temp->next = iter->second;
            temp = temp->next;
             m.erase(iter);
             
        }
        
        return h->next;
    }
};
posted @ 2021-12-14 22:39  jozon  阅读(21)  评论(0)    收藏  举报