用c++,写了个单链表类

本文介绍了一个简单的单链表实现,包括数据插入、删除、查找等功能,并通过C语言进行编码实现。

这几天开始学习数据结构,今天便写了个最简单的单链表,在头文件里定义的;

并且实现了自定义位置插入数据,删除数据,查找数据,默认添加数据功能;

不知道这算不算ADT呢,对于概念还不是很懂(笑;

只有一点点的C基础,写面向对象还不是很熟悉,希望代码不会很难看XD;

#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::cin;
using std::endl;
struct Date_{
	string name = "名字:";
	string sex = "男/女:";
	string id = "id:";
	string age = "年龄:";
	Date_ *nextone = NULL;
};
class uselinklist {
public:
	typedef Date_* link;
	uselinklist(){
		headp = NULL;
	}
	link return_head(){ return headp; }
	void addDate();//在表头插入数据
	int delectDate();//删除数据
	int insertDate();//自定义位置插入数据
	void showDate() const;//显示所有数据
	int searchDate() const;//查找数据
private:
	link headp;//头指针
};
void uselinklist::addDate(){
	link newp = new Date_;//创建一个新数据
	cout << "请输入新增的数据\n" << newp->name << endl;
	cin >> newp->name;
	cout << newp->sex << endl;
	cin >> newp->sex;
	cout << newp->id << endl;
	cin >> newp->id;
	cout << newp->age << endl;
	cin >> newp->age;
	if (headp == NULL){	headp = newp; }
	else{
		newp->nextone = headp;//在表头插入
		headp = newp;
	}
}
int uselinklist::delectDate(){
	cout << "你希望删除谁的数据" << endl;
	string name;
	cin >> name;
	link findp = headp;
	for (; findp != NULL; findp = findp->nextone){
		if (findp->name == name){
			link a = findp;
			findp = findp->nextone;
			free(a);
			cout << "删除成功!" << endl;
			return 0;
		}
	}
	cout << "找不到这个人的数据" << endl;
	return -1;
}
int uselinklist::insertDate(){
	cout << "输入你希望插入数据前一个人的名字:" << endl;
	string name;
	cin >> name;
	link findp = headp;
	for (; findp != NULL; findp = findp->nextone){
		if (findp->name == name){
			cout << "找到该人!" << endl;
			link newp = new Date_;//创建新数据
			cout << "请输入新增的数据\n" << newp->name << endl;
			cin >> newp->name;
			cout << newp->sex << endl;
			cin >> newp->sex;
			cout << newp->id << endl;
			cin >> newp->id;
			cout << newp->age << endl;
			cin >> newp->age;
			newp->nextone = findp->nextone;//插入
			findp->nextone = newp;
			return 0;
		}
	}
	cout << "无法找到该人!" << endl;
	return -1;
}
void uselinklist::showDate() const{
	link p = headp;
	for (; p != NULL; p = p->nextone){
		cout << "\n" << p->name
			<< " " << p->sex
			<< " " << p->id
			<< " " << p->age << endl;
	}
}
int uselinklist::searchDate() const{
	cout << "输入你希望查看谁的数据:" << endl;
	string name;
	cin >> name;
	link findp = headp;
	for (; findp != NULL; findp = findp->nextone){
		if (findp->name == name){
			cout << "\n" << findp->name
				<< " " << findp->sex
				<< " " << findp->id
				<< " " << findp->age << endl;
			return 0;
		}
	}
	cout << "无法找到该人!" << endl;
	return -1;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值