148链表排序 Posted on 2020-04-19 Words count in article: 224 | Reading time ≈ 1 148. 排序链表下面是题目下面是题目给出的代码模板1234567891011121314/** * 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) { }}; 因为我自己不会直接在链表上操作,所以我用了multiset存储1234567891011121314151617181920212223242526272829303132/** * 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) { multiset<int>st; ListNode*cur = head; while(cur) { //首先,把所有的链表信息都存放在multiset中,因为multiset会自己排序 st.insert(cur->val); cur = cur->next; } ListNode *dummy = new ListNode(0); ListNode *head2 = dummy; for(set<int>::iterator it = st.begin();it!=st.end();it++) { //第二步,就是每次从set中取出一个数据,建立新的节点,然后尾插法 ListNode *newNode = new ListNode(*it); dummy->next= newNode; dummy = dummy->next; } return head2->next; }}; -------------本文结束,感谢您的阅读------------- Post author: Jason Post link: https://jasonxqh.github.io/2020/04/19/148%E9%93%BE%E8%A1%A8%E6%8E%92%E5%BA%8F/ Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 3.0 unless stating additionally.