[leetcode]sort list
2015-09-08 17:34
281 查看
/** * 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分配还没有,还有其他的方法你?
相关文章推荐
- ThinkPHP3.2.3 使用常量BUILD_CONTROLLER_LIST无法生成Controller
- 【面试算法系列】已知二叉树的前序和中序遍历重建二叉树 - C语言实现
- Yii Framework 开发教程(3) 为应用添加日志
- 第2周项目2--程序的多文件组织
- f:facet标签 的用法
- RCNN的安装与简单使用
- java中方法重载和重写
- 确定public继承出来的是Is_a关系(Effective C++_32)
- poj 2763 Housewife Wind 边权的树链剖分
- iOS触摸事件学习
- RPC(Remote Procedure Call Protocol)
- 谷歌浏览器下小于12px字体的解决办法
- ApplicationContext
- Android中Context的理解与使用技巧
- mark 20150908
- Android客户端与服务器端通过DES加密认证
- Launcher 主菜单界面手机休眠后打开已经回到了待机界面
- leetcode--Find Minimum in Rotated Sorted Array II ---C++
- guibin
- php判断数据库是否连接成功的测试例子