![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/63ba0af82c184135573cbb6237400268.jpeg)
参考答案——线性链表的实现
linked_List.h头文件
#ifndef linked_List_h
#define linked_List_H
#include <iostream>
using namespace std;
template<class T>
struct node
{
T d;
node *next;
};
template<class T>
class linked_List
{
private:
node<T> * head;
public:
linked_List();
~linked_List();
void prt_linked_List();
void ins_linked_List(T, T);
int del_linked_List(T);
};
template<class T>
linked_List<T>::linked_List()
{
head = NULL;
return;
}
template<class T>
linked_List<T>::~linked_List()
{
if (head==NULL) return;
while (head->next!=NULL)
{
node<T> * p;
p = head->next;
delete head;
head = p;
}
return;
}
template<class T>
void linked_List<T>::prt_linked_List()
{
node<T> * p;
p = head;
if (p==NULL)
{
cout << "空链表! " << endl;
return;
}
do
{
cout << p->d << endl;
p = p->next;
}while(p!=NULL);
return;
}
template<class T>
void linked_List<T>::ins_linked_List(T x, T b)
{
node<T> *p, *q;
p = new node<T>;
p->d = b;
if (head==NULL)
{
head = p;
p->next=NULL;
return;
}
if (head->d==x)
{
p->next = head;
head = p;
return;
}
q = head;
while ((q->next!=NULL) && (((q->next)->d)!=x))
q = q->next;
p->next = q->next;
q->next = p;
}
template<class T>
int linked_List<T>::del_linked_List(T x)
{
node<T> *p, *q;
if (head==NULL) return(0);
if ((head->d)==x)
{
p=head->next;
delete head;
head=p;
return (1);
}
q = head;
while ((q->next!=NULL) && (((q->next)->d)!=x))
q = q->next;
if (q->next==NULL) return(0);
p = q->next;
q->next = p->next;
delete p;
return(1);
}
#endif
测试主函数
#include "linked_List.h"
int main()
{
linked_List<int> s;
cout << "第1次扫描输出链表内的元素" << endl;
s.prt_linked_List();
s.ins_linked_List(10,10);
s.ins_linked_List(10,20);
s.ins_linked_List(10,30);
s.ins_linked_List(40,40);
cout << "第2次扫描输出链表内的元素" << endl;
s.prt_linked_List();
if (s.del_linked_List(30))
cout << "删除元素:30" << endl;
else
cout << "链表中无元素: 30" << endl;
if (s.del_linked_List(50))
cout << "删除元素:50" << endl;
else
cout << "链表中无元素: 50" << endl;
cout << "第3次扫描输出链表内的元素" << endl;
s.prt_linked_List();
return 0;
}
运行结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/1d93dff4ec9c1843cf4bb8c743bf5562.png)