博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
2.1
阅读量:2382 次
发布时间:2019-05-10

本文共 1020 字,大约阅读时间需要 3 分钟。

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
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循环,还需要加强训练

转载地址:http://ubyab.baihongyu.com/

你可能感兴趣的文章
Redis 集群功能说明
查看>>
linux 下 free的用法
查看>>
oracle11gR2在RedHat5上前期安装配置脚本
查看>>
sar的用法
查看>>
Cocos2dx3.2从零开始【四】继续。
查看>>
Unable to execute dex: Multiple dex files define 解决方法
查看>>
Cocos2dx3.2从零开始【五】
查看>>
字符画
查看>>
JS读取DropDownList中的值
查看>>
进度条例子
查看>>
WordPress注册支持中文用户名的解决办法
查看>>
设置WordPress评论头像为圆角鼠标触碰后旋转效果
查看>>
WordPress:删除多说插件的版权信息
查看>>
查询表中两个条件下的数目,按三列组成表
查看>>
WinForm下禁止TextBox右键菜单
查看>>
C#_winform_DataGridView_的18种常见属性
查看>>
C# 扩展系统类string的方法
查看>>
webBrowser强制在本窗口打开,禁止在新窗口打开
查看>>
C#获取CPU序列号代码、硬盘ID、网卡硬件地址等类文件
查看>>
Html常用符号
查看>>