2.1

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值