求助大佬,创建一个没有重复元素的单链表,出现错误怎么改呢
#include <iostream>using namespace std;
template <class T>
struct node
{
T data;
node<T>* next;
};
template <class T>
class link
{
node<T>* first;
public:
link()
{
first = new node<T>;
first->next = NULL;
}
link(T a[], int length)
{
first = new node<T>;
first->next = NULL;
node<T>* r = first;
node<T>* w = new node<T>;//先插入第一个
w->data = a[0];
r->next = w;//插入的结点放在first之后
r = w;//r指向查插入的第一个结点
for (int i = 1; i < length; i++)
{
int flag = 0;
node<T>* s=first->next;
while (s != NULL)//寻找是否已经有相同的元素
{
if (s->data == a[i])
{
flag = 1;
break;
}
s = s->next;
}
if (flag == 0)//没有相同的元素,将数组目前元素尾插法插入链表
{
node<T>* p = new node<T>;
p->data = a[i];
r->next = p;
r= p;
}
}
r->next = NULL;//最后将最后一个结点的next域置空
}
void show()
{
node<T> * p = first->next;
while (p != nullptr)
{
cout << p->data << " ";
p = p->next;
}
}
};
int main()
{
int a[100];
int m;
cin >> m;
for (int i = 0; i < m; i++)
{
cin >> a[i];
}
link<int> link2(a, m);
link2.show();
return 0;
}