题意:
构造一个单向链表,从单向链表中删除指定值的节点,并输出。
注意:链表的值不能重复。
方法一:
map模拟链表
思路:根据题意中链表的值不能重复,则可以用map模拟链表的实现。首先,依据map的映射关系构建一个链表;
然后,遍历链表输出,输出的时候排除指定值的节点。
![]()
#include <bits/stdc++.h>
using namespace std;
int main(){
unordered_map<int,int> m;//链表的值不能重复
int n,x,y,a,b;
cin >> n >> x;
for(int i=0;i<n-1;i++){
cin >> a >> b;
if(m.count(b)==0)//构建链表
m[b]=a;
else{
m[a]=m[b];//插入元素
m[b]=a;
}
}
cin >> y;
int p=x;//遍历指针p
while(m.count(p)){//遍历输出
if(p!=y){
cout << p << " ";
}
p=m[p];
}
if(p!=y)
cout << p << endl;
return 0;
}
时间复杂度:
空间复杂度:![]()
方法二:
链表
思路:构造链表。
根据输入模拟链表的插入操作。最后,循环链表,并输出值不为给定值的节点。
#include <bits/stdc++.h>
using namespace std;
struct node{
int val;
node *next;
node(int x):val(x),next(nullptr){}
};
int main(){
int n,x,y,a,b;
cin >> n >> x;
node *head=new node(x);//新建头结点
for(int i=0;i<n-1;i++){
cin >> a >> b;
node *p=new node(a);//新建新节点
node *q=head;
while(q&&q->val!=b){//循环找到值为b的节点
q=q->next;
}
p->next=q->next;//插入操作
q->next=p;
}
cin >> y;
node *p=head;
while(p){
if(p->val!=y){//输出值不为y的节点
cout << p->val << " ";
}
p=p->next;
}
cout << endl;
return 0;
}
时间复杂度:
空间复杂度:![]()



京公网安备 11010502036488号