//LinkList.h
#ifndef LinkList_H
#define LinkList_H
template<class DataType>
struct Node
{
DataType data;
Node <DataType>* next;
};
template<class DataType>
class LinkList
{
public :
LinkList();
LinkList(DataType a[], int n);
~LinkList();
int Locate(DataType x);
void Insert(int i, DataType x);
const void PrinList();
DataType Delete(int i);
private:
Node<DataType>* first;
};
#endif
//LinkList.cpp 单链表的实现
#include<iostream>
using namespace std;
#include<LinkList.h>
template<class DataType>
LinkList<DataType>::LinkList()
{
first = new Node <DataType>;
first->next = NULL;
}
template<class DataType>
LinkList<DataType>::LinkList(DataType a[], int n)
{
Node <DataType>* r, * s;
first = new Node<DataType>;
r = first;
for (int i = 0; i < n; i++)
{
s = new Node<DataType>;
s->data = a[i];
r->next = s; r = s;
}
r->next = NULL;
}
template<class DataType>
LinkList<DataType>::~LinkList()
{
Node<DataType>* q = NULL;
while (first != NULL)
{
q = first;
first = first->next;
delete q;
}
}
template<class DataType>
void LinkList<DataType>::Insert(int i, DataType x)
{
Node<DataType>* p = first, * s = NULL;
int count = 0;
while (p != NULL && count < i - 1)
{
p = p->next;
count++;
}
if (p == NULL)throw"位置";
else
{
s = new Node<DataType>; s->data = x;
s->next = p->next; p->next = s;
}
}
template<class DataType>
DataType LinkList<DataType>::Delete(int i)
{
Node <DataType>* p = first, * q = NULL;
DataType x;
int count = 0;
while (p != NULL && count < i - 1)
{
p = p->next;
count++;
}
if (p == NULL || p->next == NULL)
throw "位置";
else
{
q = p->next; x = q->data;
p->next = q->next;
delete q;
return x;
}
}
template<class DataType>
int LinkList <DataType>::Locate(DataType x)
{
Node<DataType>* p = first->next;
int count = 1;
while (p != NULL)
{
if (p->data == x)return count;
p = p->next;
count++;
}
return 0;
}
template<class DataType>
void LinkList<DataType>::PrinList()
{
Node<DataType>* p = first->next;
while (p != NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
//LinkList_main.cpp 主函数
#include <冲.cpp>
#include<iostream>
using namespace std;
void main()
{
int r[5] = { 1,2,3,4,5 };
LinkList<int>L(r, 5);
cout << "执行插入操作前数据为:" << endl;
L.PrinList();
try
{
L.Insert(2, 9);
}
catch (char* s)
{
cout << s << endl;
}
cout << "执行插入操作后数据为:" << endl;
L.PrinList();
cout << "值为4的元素位置为:";
cout << L.Locate(4) << endl;
cout << "执行删除操作前数据为:" << endl;
L.PrinList();
try
{
L.Delete(1);
}
catch (char* s)
{
cout << s << endl;
}
cout << "执行删除操作后的数据为:" << endl;
L.PrinList();
}
手打教材单链表
最新推荐文章于 2023-02-11 23:10:16 发布