#include <bits/stdc++.h>
using namespace std;
template <typename Elemtype>
class LinkedList
{
private:
typedef struct LNode
{
Elemtype data;
LNode *next;
} LNode, *Linklist;
Linklist head;
public:
LinkedList() //构造
{
head = new LNode;
head->next = NULL;
cout << "constructed" << endl;
}
~LinkedList() //析构
{
Linklist prev;
while (head)
{
prev = head;
head = head->next;
delete prev;
}
cout << "destroyed" << endl;
}
Linklist begin() //头节点(无意义)
{
//此时q->next==NULL
return head;
}
Linklist end() //尾节点 (有意义)
{
Linklist q;
q = head;
while (q->next)
{
q = q->next;
}
//此时q->next==NULL
return q;
}
void insert(Linklist pos, Elemtype x) //按位置后插入
{
Linklist add = new LNode;
add->data = x;
add->next = pos->next;
pos->next = add;
}
void insert(int pos, Elemtype x) //按下标后插入
{
Linklist p;
p = head;
while (p->next)
{
p = p->next;
pos--;
if (pos == 0)
{
Linklist add = new LNode;
add->data = x;
add->next = p->next;
p->next = add;
return;
}
}
}
void erase(Linklist pos) //按位置删除
{
Linklist q;
q = head;
while (q->next)
{
if (q->next == pos)
{
q->next = pos->next;
delete pos;
return;
}
q = q->next;
}
}
void erase(int pos) //按下标删除
{
Linklist q;
q = head;
while (q->next)
{
pos--;
if (pos == 0)
{
q->next = q->next->next;
delete q->next;
return;
}
q = q->next;
}
}
bool empty() //判断是否为空
{
Linklist p;
p = head;
if (p->next == NULL)
{
return true;
}
else
{
return false;
}
}
int size() //个数
{
Linklist p;
p = head;
int cnt = 0;
while (p->next)
{
p = p->next;
cnt++;
}
return cnt;
}
Elemtype Getelem(int pos) //返回数(如果超出上限会re)
{
Linklist p;
p = head;
while (p->next)
{
p = p->next;
pos--;
if (pos == 0)
{
return p->data;
}
}
}
int find(Elemtype x) //查找第一个为x的元素的位置,否则抛出-1
{
Linklist p;
p = head;
int pos = 0;
while (p->next)
{
p = p->next;
pos++;
if (p->data == x)
{
return pos;
}
}
return -1; //抛出异常
}
void print()
{
Linklist p;
p = head;
if (p->next == NULL)
{
cout << "Linkedlist is empty" << endl;
}
else
{
cout << "front: ";
while (p->next)
{
p = p->next;
cout << p->data << " ";
}
cout << endl;
}
}
// // //待完成内容
// void Linkedlist_intersection(LinkedList &b) //a交b
// {
// }
// void Linkedlist_union(LinkedList &b) //a并b
// {
// }
// void Linkedlist_difference(LinkedList &b) //a-b的差集
// {
// }
// void Linkedlist_sort(LinkedList &b) //a排序
// {
// }
};
07-14
656
07-07
142