zoukankan      html  css  js  c++  java
  • [leetcode]sort list

    /**
    * 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分配还没有,还有其他的方法你?


    版权声明:本文博主原创文章,博客,未经同意不得转载。

  • 相关阅读:
    编译预处理指令:文件包含指令、宏定义指令、条件编译指令
    多文件协作,extern、static、头文件
    函数间参数传递的3种方式
    函数的定义与调用
    编码标准:ASCII、GBK、Unicode(UTF8、UTF16、UTF32)
    插入字符
    Windows Vista for Developers——第四部分:用户帐号控制(User Account Control,UAC)
    C# 获取QQ好友列表信息的实现
    C# 获取QQ群数据的实现
    QQ登陆功能的实现2
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/4792411.html
Copyright © 2011-2022 走看看