2.1-链表去重
来源:互联网 发布:带着淘宝混异世文汇吧 编辑:程序博客网 时间:2024/06/03 19:43
Write code to remove duplicates from an unsorted linked list.
FOLLOW UP
How would you solve this problem if a temporary buffer is not allowed?
链表去重
1.用hash来检测重复,O(n)
2.遍历链表的同时,每次检索之前的所有元素是否有重复,有的话就删除当前节点, O(n^2)
#include <iostream>#include <hash_map.h>using namespace std;struct ListNode{ int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {}};void show(ListNode *head){ while(head) { cout<<head->val; head = head->next; } cout<<endl;}ListNode *createLinkedlist(int array[], int len){ ListNode *cur = new ListNode(0); ListNode *head=cur; for(int i=0; i<len; i++) { ListNode *p = new ListNode(array[i]); cur->next=p; cur=cur->next; } cur->next=NULL; return head->next;}void removeDuplicates_Hash(ListNode *head){ if(head==NULL || head->next==NULL) return; ListNode *cur=head,*pre=head; hash_map<int, int> hashmap; while(cur) { if(hashmap.find(cur->val) != hashmap.end())//exist { pre->next=cur->next; } else { hashmap[cur->val]=1; pre=cur; } cur = cur->next; }}void removeDuplicates_O2(ListNode *head){ if(head==NULL || head->next==NULL) return; ListNode *cur=head->next,*pre=head; ListNode *pre_itor=head; while(cur) { while(pre_itor!=cur) { if(pre_itor->val==cur->val) { pre->next=cur->next; break; } pre_itor = pre_itor->next; } if(pre_itor==cur) pre=cur; cur = cur->next; pre_itor=head; }}int main(){ int a[] = {1,2,3,4,5,2,3,2,1,1,1,1}; ListNode *head = createLinkedlist(a,12); show(head); removeDuplicates_Hash(head); show(head); ListNode *head2 = createLinkedlist(a,12); removeDuplicates_O2(head2); show(head2); return 0;}
0 0
- 2.1-链表去重
- 链表去重
- 链表去重
- 链表去重
- 链表去重
- 链表去重
- 排序链表去重
- 链表去重2
- PAT链表去重
- L2-2. 链表去重
- PAT L2-2 链表去重
- L2-002. 链表去重
- L2-002. 链表去重
- PAT L2-002 链表去重
- PATL2-002. 链表去重(模拟)
- L2-002. 链表去重
- L2-002. 链表去重
- L2-002. 链表去重
- oracle 反斜杠 /
- [水]ZOJ1025
- 人有多大懒,才有多大闲 (评论『卓有成效的程序员』)
- Linux2.6.36/37下移植yaffs2
- linux多进程编程
- 2.1-链表去重
- 好代码是廉价的代码
- 三种东西永远不要放到数据库里
- fl2440 开发板环境配置(仅供个人参考,记忆力不好)
- C++设计模式-Singleton
- Java中能帮助你快速的进行添、删、查、改的SqlHelper
- for 循环为何可恨?
- Hive日志调试
- win7格式化ubuntu分区后轻松解决grub rescue的 问题