C++链表类
个人写的学生管理系统相关的链表类操作
- 存放数据的节点node类
class node
{
public:
node();
~node();
char student[20];//学生姓名
long int ID;//学号
int chinese;//成绩
int math;
int english;
node* next;
};
- 存放函数的list类
class list
{
public:
list();
~list();
int lenth;//链表长度
void trave();//遍历
void add();//从尾部添加信息
int add(int n);//添加结点到第n个位置
int delet(int n);//删除第n位的结点
int change(int n);//修改学生信息
node* head;
private:
node* tail;
};
- 在list的构造函数中创建链表的前两个节点
list::list()//构造函数
{
head = new node;//链表头
tail = new node;//第二个节点
head->next = tail;//连接
tail->next = nullptr;//尾巴置空
lenth = 2;//链表长度
}
- 遍历
void list::trave()//遍历
{
cout << "姓名 学号 语文 数学 英语" << endl;
out << "姓名 学号 语文 数学 英语" << endl;
node* pre = head;
while (pre != nullptr)
{
cout << pre->student << " " << pre->ID << " " << pre->chinese << " " << pre->math << " " << pre->english << endl;
out << pre->student << " " << pre->ID << " " << pre->chinese << " " << pre->math << " " << pre->english << endl;
pre = pre->next; //循环输出
}
}
- 从尾部添加信息
void list::add()//从尾部添加
{
node* pre = head;//存储头指针
while (pre->next!= nullptr)//将指针移向尾部
{
pre = pre->next;
}
char c = '\0';
cout << "添加信息吗(y/n)" << endl;
cin >> c;
while (c == 'y')
{
pre->next = new node; //新建一个节点
pre = pre->next;
pre->next = nullptr; //尾部置空
lenth++; //添加一次,长度加一
cout << "添加信息吗(y/n)" << endl;//循环判断
cin >> c;
}
trave();
}
- 任意位置添加信息
int list::add(int n)//添加新节点到第n位
{
if (n <= 0 || n > lenth+1)
{
cout << "不是有效长度" << endl;
}
else
{
node* pre = head; //存储head
node* pp = nullptr;
node* rp = nullptr;
if (n > 1 && n < lenth + 1)
{
while (--n) //循环移动指针
{
pp = pre;
pre = pre->next;
}
rp = pre; //存储原位置的节点地址
pre = new node; //新建节点,并改变相应位置节点的指针
pp->next = pre; //next指向新节点
pre->next = rp; //新节点的next指向原位置节点的首地址
lenth++;
trave();
}
if (n == 1) //添加在首位
{
head = new node; //head变为新节点的首地址
head->next = pre;
lenth++;
trave();
}
if (n == lenth + 1) //添加在末尾
add(); //调用add函数
}
return 0;
}
- 删除节点
int list::delet(int n) //删除第n位节点
{
if (n <= 0 || n > lenth)
{
cout << "不是有效长度" << endl;
return 1;
}
node* pre = head;
node* pp = nullptr;
if(n == 1) //删除首位
{
pre = pre->next;
delete head;
head = pre;
lenth--; //长度减一
trave();
}
if (n == lenth) //删除末尾结点
{
while (pre -> next != nullptr)//循环移动指针至末尾
{
pp = pre;
pre = pre->next;
}
pp->next = nullptr;//置空
delete pre;
lenth--;
trave();
}
if (n > 1 && n < lenth)
{
while (--n) //循环移动指针
{
pp = pre;
pre = pre->next;
}
pp->next = pre->next;//改变指向
delete pre;
lenth--;
trave();
}
return 0;
}
- 改变信息
int list::change(int n)//改变信息
{
if(n>lenth)
{
cout << "不是有效长度" << endl;
return 1;
}
node* pre = head;
while (--n) //循环移动指针
pre = pre->next;
cout << "依次输入姓名、学号、语文、数学、英语" << endl;
cin >> pre->student >> pre->ID >> pre->chinese >>pre->math>> pre->english;
trave();
return 0;
}