头文件的源代码:
#ifndef head_1
#define head_1
struct Node
{
Node *next;
int data;
};
class list
{
public:
list();
~list();
list(int a[], int n);
void Insert(int a, int b);
void Delete(int c);
void Locate(int d);
void Print();
private:
Node *first;
};
#endif
成员函数的源代码:
#include<iostream>
#include"head.h"
using namespace std;
list::list(int a[],int n)
{
Node *r,*s;
first = new Node;
r = first;
for (int i = 0; i < n; i++)
{
s = new Node;
s->data = a[i];
r->next = s;
r = s;
}
r->next = NULL;
}
void list::Insert(int a, int b)
{
Node *p = first, *s=NULL;
int count = 0;
while (p != NULL&&count < a - 1)
{
p = p->next;
count++;
}
if (p == NULL)cout << "位置错误" << endl;
else{
s = new Node; s->data = b;
s->next = p->next;
p->next = s;
}
}
void list::Delete(int c)
{
Node *p = first, *q = NULL;
int x;
int count = 0;
while (p != NULL&&count < c - 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;
}
}
void list::Locate(int d)
{
Node *p = first->next;
int count = 1;
while (p!=NULL)
{
if (p->data == d)cout << "其位置:"<<count<<endl;
p = p->next;
count++;
}
}
void list::Print()
{
Node *p = first->next;
while (p != NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
list::~list()
{
Node *q = NULL;
while (first!=NULL)
{
q = first;
first = first->next;
delete q;
}
}
主函数的源代码:
#include<iostream>
#include"head.h"
using namespace std;
void main()
{
const int maxsize = 100;
int A;
int r[maxsize];
cout << "请输入要存储的个数:";
B:
cin >> A;
if (A > maxsize || A < 0)
{
cout << "超过限额,请重新输入:";
goto B;
}
else
{
cout << "依次输入数字:";
for (int q = 0; q < A; q++)
cin >> r[q];
}
list L(r, A);
cout << "执行插入前的数据为:";
L.Print();
L.Insert(1, 9);
cout << "执行插入后的数据为:";
L.Print();
cout << "请输入要查找的数据:";
int k;
cin >> k;
L.Locate(k);
cout << "执行删除前的数据为:";
L.Print();
cout << "请输入要删除的数据的位置:";
int h;
cin >> h;
L.Delete(h);
cout << "执行删除后的数据为:";
L.Print();
system("pause");
}