这几天开始学习数据结构,今天便写了个最简单的单链表,在头文件里定义的;
并且实现了自定义位置插入数据,删除数据,查找数据,默认添加数据功能;
不知道这算不算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;
}
本文介绍了一个简单的单链表实现,包括数据插入、删除、查找等功能,并通过C语言进行编码实现。
4894

被折叠的 条评论
为什么被折叠?



