2.1
来源:互联网 发布:java界面编程代码 编辑:程序博客网 时间:2024/06/11 05:54
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?
分析:如何允许使用额外空间,我们可以使用map来记录已经存在的节点,遇到重复的节点就删除;如果不允许使用额外空间,只能每次枚举一个节点,然后遍历完数组,将与这个元素相同的元素删除,时间复杂度为O(n^2)
使用额外空间的方法:
struct Node{int data;Node* next;};map<int,int> mp;void remove_dup(Node* head){if(head==NULL) return;Node* before=head;Node* cur=before->next;mp[before->data]=1;while(cur!=NULL){if(mp.count(cur->data)){before->next=cur->next;Node* del=cur;cur=cur->next;delete del;//我认为应该将不用的指针删掉}else{before=cur;cur=cur->next;mp[before->data]=1;}}}
不使用额外空间的方法:
void remove_dup(Node* head){if(head==NULL) return;Node* left=head;Node* before=head;while(left!=NULL){Node* cur=left->next;before=left;while(cur!=NULL){if(cur->data==left->data){before->next=cur->next;Node* del=cur;cur=cur->next;delete del;}else{before=cur;cur=cur->next;}}left=left->next;}}评:在纸上第一遍写代码的时候,忘记了写cur的while循环,还需要加强训练
- 2.1
- 2.1
- 2.1
- 2.1
- 2.1
- 2.1
- 2.1
- 2.1
- 2.1.7-2.1.10
- 汇编2.1
- 2.1. Introduction
- 2.1程序结构
- 2.1看盘
- Detours 2.1
- Lift 2.1
- 2.1 holstein
- 2.1 Hamming
- 2.1 frac1
- MAC共享
- 云计算之路:AWS, Azure, Aliyun, UCloud提供的Windows操作系统
- IOS开发之cocoa多线程浅析
- JAVA基础:二维数组初始化
- UVa 127: "Accordian" Patience
- 2.1
- 个人备注 JS使用问题集锦
- 【SQL】查询语句中in和exists的区别
- RedHat系统下Samba服务器配置详解及具体应用实例
- 区分a++与++a
- 多终端管理器tmux使用详解
- ubuntu环境下 Eclipse 反编译插件 jadclipse
- Redhat静态IP配置
- 用 javascript 判断 IE 版本号