单链表的实现

头文件的源代码:

#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");
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值