单链表功能
能正常实现各项功能,但不能保证健壮性,
学生类:
class Student {
string name;
int number;
int score;
public:
string getName() {
return this->name;
}
Student(string _name = " ", int _number = 0, int _score = 0) {
this->name = _name;
this->number = _number;
this->score = _score;
}
//运算符重载
friend ostream& operator<<(ostream& out, const Student& s) {
out <<"姓名:"<< s.name << " 学号:" << s.number << " 成绩:" << s.score;
return out;
}
friend istream& operator>>(istream& in, Student& s) {
cin >> s.name >> s.number >> s.score;
return in;
}
};
链表结点类:
//链表结点类
class LNode {
public:
Student data;//数据域
LNode* next;
LNode() {
this->next = NULL;
}
};
链表类:
class LinkList {
LNode* LHead;//声明一个头指针
public:
LinkList();
~LinkList();
//尾插法
void headInsert(string name,int number,int score);
//头插法按照位序插入
void headInsert(int n,Student s);
//遍历链表输出
void traverseList();
//删除指定位置结点
void deleteList(int i);
//根据姓名按值查找
Student locateList(string name);
//按序号查找
Student getList(int i);
//获取链表长度
int getLenght();
};
链表初始化:
LinkList::LinkList() {
this->LHead = new LNode;
LHead->next = NULL; //初始化为空链表
if (this->LHead == NULL) {
cout << "分配内存失败";
return;
}
}
尾插法建立链表:
//尾插法建立链表
void LinkList::headInsert(string name, int number, int score) {
LNode* p = LHead;
while (p->next)
p = p->next;
LNode* q = new LNode;
q->data = Student(name, number, score);
p->next = q;
}
在指定位置使用头插法:
//在指定位置插入
void LinkList::headInsert(int n, Student e) {
if (n < 1 || n>getLenght()) {
cout << "插入位置错误!";
}
LNode* p; //p指向当前扫描的点
int j = 0; //p指向第几个
p = LHead; //p指向头结点
while (p != NULL && j < n - 1) {
p = p->next;
j++;
}
if (p == NULL)
cout << "error";
LNode* s = new LNode;
s->data = e;
s->next = p->next;
p->next = s;
cout << "头插法按位置插入成功" << endl;
}
根据姓名查询:
/根据姓名查询
Student LinkList::locateList(string name) {
LNode* p = LHead->next;
for (int i = 0; i < getLenght(); i++) {
if (p && p->data.getName() != name)
p = p->next;
}
return p->data;
}
遍历链表:
void LinkList::traverseList() {
LNode* p = LHead;
p = p->next;
if (LHead == NULL || LHead->next == NULL)
cout << "链表不存在或者为空!" << endl;
while (p)
{
cout << p->data << endl;
p = p->next;
}
}
获取长度:
int LinkList::getLenght() {
int count = 0;
LNode* p = LHead->next;
while (p!=NULL)
{
count++;
p = p->next;
}
return count;
}
删除指定位置元素:
void LinkList::deleteList(int i) {
LNode* p = LHead;
int j = 0;
if (i<0 || i>getLenght()) {
cout << "请输入正确的删除位置1-" << getLenght() << endl;
}
if (!(p->next))
cout << "链表为空" << endl;
while (p->next && j < i - 1) {
p = p->next;
j++;
}
LNode* q = new LNode;
q = p->next;
p->next = q->next;
delete q;
cout << "删除成功" << endl;
}
根据指定位置获取数据:
Student LinkList::getList(int n) {
int j = 1;
LNode* p = LHead->next;
if (n == 0)
return LHead->data;
if (n < 1)
cout << "输入非法";
while (p && j < n) {
p = p->next;
j++;
}
return p -> data;
}
析构函数:
LinkList::~LinkList() {
delete LHead;
}