1 #include<iostream>
2 using namespace std;
3 //定义结点类型
4 template<class T> //T为虚拟类型
5 struct node
6 {
7 T d;
8 node *next;
9 };
10 //定义线性链表类
11 template<class T> //模板声明,数据元素虚拟类型为T
12 class linked_List
13 {
14 private: //数据成员
15 node<T> *head; //链表头指针
16 public: //成员函数
17 linked_List(); //构造函数,建立空链表
18 void prt_linked_List(); //扫描输出链表中的元素
19 void ins_linked_List(T,T); //在包含元素x的结点前插入新元素b
20 int del_linked_List(T); //删除包括元素x的结点
21 };
22 //建立空链表
23 template<class T>
24 linked_List<T>::linked_List()
25 {
26 haed=NULL;
27 return;
28 }
29 //扫描输出链表中的元素
30 template<class T>
31 void linked_List<T>::prt_linked_List()
32 {
33 node<T> *p;
34 p=head;
35 if (p==NULL)
36 {
37 cout<<"空链表!"<<endl;
38 return;
39 }
40 do
41 {
42 cout<<p->d<<endl;
43 p=p->next;
44 } while (p!=NULL);
45 return;
46 }
47 //在包含元素x的结点前插入新元素b
48 template<class T>
49 void linked_List<T>::ins_linked_List(T x,T b)
50 {
51 node<T> *p ,*q;
52 p=new node<T>; //申请一个新结点
53 p->d=b; //置新结点的数据域
54 if (head==NULL) //原链表为空
55 {
56 head=p;
57 p->next=NULL;
58 return;
59 }
60 if (head->d==x) //在第一个结点前插入
61 {
62 p->next=head;
63 head=p;
64 return;
65 }
66 q=head;
67 while ((q->next!=NULL)&&(((q->next)->d)!=x))
68 {
69 q=q->next; //寻找包含元素x的前一个结点q
70 }
71 p->next=q->next; //新结点p插入到结点q之后
72 q->next=p;
73 return;
74 }
75 //删除包含元素x的结点元素
76 template<class T>
77 int linked_List<T>::del_linked_List(T x)
78 {
79 node<T> *p ,*q;
80 if (head==NULL)return(0); //链表为空,无删除的元素
81 if (head->d==x) //删除第一个结点
82 {
83 p=head->next;
84 delete head;
85 head=p;
86 return(1);
87 }
88 q=head;
89 while ((q->next!=NULL)&&(((q->next)->d)!=x))
90 q=q->next;; //寻找包含元素x的前一个结点q
91 if (q->next==NULL)return(0); //链表中无删除的元素
92 p=q->next; //删除q的下一个结点p
93 q->next=p->next;
94 delete p; //释放结点p的存储空间
95 return(1);
96 }