/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
* Sort a linked list in O(n log n) time using constant space complexity.
*/
#include<iostream>
#include<fstream>
#include<vector>
#include<map>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *sortList(ListNode *head) {
if (head == NULL || head->next == NULL)return head;
map<int, vector<ListNode*>> mp;
ListNode* pnode = head;
while (pnode)
{
mp[pnode->val].push_back(pnode);
pnode = pnode->next;
}
map<int, vector<ListNode*>>::iterator it = mp.begin();
head = NULL;
ListNode* cur = NULL;
for (; it != mp.end(); it++)
{
vector<ListNode*> vec = (*it).second;
for (int i = 0; i < vec.size(); i++)
{
if (head == NULL){
head = vec[i];
cur = vec[i];
}
else{
cur->next = vec[i];
cur = cur->next;
}
}
}
cur->next = NULL;
return head;
}
};
int main(){
fstream fin("test.txt");
struct ListNode* head(0);
int val = 0;
//string s1 = "asdf";
//string s2(s1);
//if (&s1 == &s2){
// int a = 1;
//}
while (fin >> val){
if (NULL == head){
head = new ListNode(val);
}
else {
ListNode *temp = head;
while (temp->next != NULL)
temp = temp->next;
temp->next = new ListNode(val);
}
}
Solution solution;
ListNode *new_head = solution.sortList(head);
return 0;
}
主函數裏關於鏈表的建立,使用了new從自由存儲區(堆)中分配了內存,鏈表一直使用到程序結束,有必要顯示的用delete進行內存釋放嗎?
關於鏈表的建立可以不使用new或malloc進行分配嗎,有其他的方法嗎?