用单链表保存m个整数,结点的结构为(data,next),且|data|≤n(n为正整数)。现要求设计一个时间复杂度尽可能高效的算法,对于链表中data的绝对值相等的结点,仅保留第一次出现的结点而删除其余绝对值相等的结点。
/*
单链表中保存M个整数,设计一个时间复杂度尽可能高效的算法,
对于链表中绝对值相等的元素(|data|<n)(假设此题中n=100),
只保留第一次出现的节点,删除其余的节点。
如:15->(-3)->(-15)->3 得:15->(-3)
*/
//以空间换时间
#include<iostream>
#include<cstring>
using namespace std;
typedef struct stu
{
int num;
stu* next;
}node,*nodelist;
nodelist creat_list(nodelist L)
{
int n;
cout<<"请输入要添加的学生人数"<<endl;
cin>>n;
while(n--)
{
nodelist p=new node;
cout<<"输入值:"<<endl;
cin>>p->num;
p->next=L;
L=p;
}
return L;
}
void display(nodelist L)
{
nodelist p;
for(p=L;p!=NULL;p=p->next)
{
cout<<p->num<<" ";
}
cout<<endl;
}
nodelist delete_result(nodelist L)
{
nodelist p1=L,p2;
int a[101]={0};
//memset(a,0,sizeof(a));
while(p1)
{
int temp;
if(p1->num>0) temp=p1->num;
else temp=-(p1->num);
//int temp=p1->num?p1->num:-(p1->num);
if(!a[temp])a[temp]=1,p2=p1;
else
{
p2->next=p1->next;
}
p1=p1->next;
}
return L;
}
int main()
{
nodelist L=NULL;
L=creat_list(L);
display(L);
L=delete_result(L);
display(L);
while(L)
{
nodelist temp=L;
L=L->next;
delete temp;
}
return 0;
}