总源代码在最后
- 双向链表:
template<typename T>
struct Node
{
T data;
Node* next;
Node* prior;
};
- 链表集合类
template<typename T>
class ListSet
{
public:
ListSet() ;
ListSet(const ListSet<T>& Set);
~ListSet();
int getlength()const ;
int findRepeated(T element);
void push(T element);
void pop();
void deleteelement(int index);
void insert(int index, T element);
void print();
T& operator[](int index);
Node<T>* GetelementNode(int index)const;
void MinusAnotherSet(ListSet & set);
friend ListSet<T> UnionSet(ListSet<T>& Set1, ListSet<T>& Set2);
friend ListSet<T> IntersectionSet(ListSet<T> & Set1, ListSet<T> &Set2);
private:
Node<T>* head;
int length;
- 构造函数
ListSet() :length(0)
{
head = new Node<T>;
head->next = head;
head->prior = head;
}
- 复制构造函数
ListSet(const ListSet<T>& Set):length(0)
{
head = new Node<T>;
head->next = head;
head->prior = head;
Node<T>* p = Set.GetelementNode(1);
for (int i = 1; i <= Set.getlength(); i++)
{
this->push(p->data);
p = p->next;
}
}
- 析构函数
~ListSet()
{
while (length) pop();
delete head;
}
- 获取长度
int getlength()const { return length; }
- 查重,若重返回下标,若无返回0
int findRepeated(T element)
{
Node<T>* p = head;
for (int i = 1; i <= length; i++)
{
p = p->next;
if (element == p->data) return i;
}
return 0;
}
- push入表
void push(T element)
{
if (findRepeated(element))
{
cout << "element repeated is not supported by set" << endl;
return;
}
Node<T>* s = new Node<T>;
s->data = element;
head->prior->next = s;
s->prior = head->prior;
s->next = head;
head->prior = s;
length&