自己做鏈表的題很容易弄錯,感覺對鏈表太不熟悉了。需要加強對鏈表的練習。
這種鏈表題有時感覺思路很簡單,但是在寫代碼的過程中會發現處理起來要十分的細心。
下面代碼記錄兩種實現方法(都是別人實現的方法)。
第一種方法(代碼裏註釋掉的部分):不滿足題目要求
創建一個map,記錄出現的數字及其出現的次數,然後遍歷map賦值給鏈表。
第二種方法:原文鏈接
1、設置快慢指針分割鏈表,遞歸;
2、對分割後的鏈表進行排序,合併兩個鏈表。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode *dummy=new ListNode (0), *p=dummy;
while(l1 && l2){
if(l1->val >= l2->val){
p->next=l2;
l2=l2->next;
}
else{
p->next=l1;
l1=l1->next;
}
p=p->next;
}
if(l1) p->next=l1;
if(l2) p->next=l2;
return dummy->next;
}
ListNode* sortList(ListNode* head) {
if(!head || !head->next) return head;
ListNode *fast=head, *slow=head, *pre=head;
while(fast && fast->next){
pre=slow;
slow=slow->next;
fast=fast->next->next;
}
pre->next=NULL;
head=sortList(head);
slow=sortList(slow);
return mergeTwoLists(head,slow);
/**
map<int, int> nums;
ListNode* p = head;
while (p) {
nums[p->val]++;
p = p->next;
}
p = head;
map<int, int>::iterator iter = nums.begin();
while (iter != nums.end()) {
for (int i = 0; i < iter->second; ++i) {
p->val = iter->first;
p = p->next;
}
iter++;
}
return head;
**/
}
};