#include<iostream>
#include<fstream>
#include<string>
#include<iomanip>
using namespace std;
struct student
{
int sID;
string sName;
student *next;
};
class LinkQueue
{
public:
LinkQueue();//构造空队列
~LinkQueue();//释放链队各节点的存储空间
student *InQueue();//元素s从队尾入队
student *addQueue(int num);//从第num个元素后入队 num=0就认为是从头指针前入队
student *DeQueue(int num);//删除第num个元素
student *OrderQueue();//把学号按从小到大排序
void PrintfQueue();
void save();
student* read(char *filename);//待更新
private:
student *front;//队头指针
student *rear;//队尾指针
int lengthQueue;//链表长度
};
LinkQueue::LinkQueue()
{
lengthQueue = 0;
front = new student;
front->next = NULL;
rear = front;
}
LinkQueue::~LinkQueue()
{
student *p;
while (front != NULL)
{
p = front;
front = front->next;
delete p;
}
}
student *LinkQueue::InQueue()
{
student *p1, *p2;
p1 = new student;
front = p1;
cout << "please input sID and sName:(end with sID=0)" << endl;
cin >> p1->sID >> p1->sName;
if (p1->sID == 0) front = NULL;
while (p1->sID != 0)
{
p2 = new student;
cout << "please input sID and sName:(end with sID=0)" << endl;
cin >> p2->sID >> p2->sName;
if (p2->sID == 0)
{
p1->next = NULL;
}
else
{
p1->next = p2;
}
//p3 = p1;
p1 = p2;
//rear = p3;
}
return front;
}
void LinkQueue::PrintfQueue()//把队列里的元素都打印
{
student *pf;
pf = front;
while (pf != NULL)
{
cout << pf->sID << " " << pf->sName << endl;
pf = pf->next;
}
}
void LinkQueue::save()//关闭前保存所有的数据
{
student *p;
p = front;
ofstream outfile("fl1.dat", ios::out);//ios::app 覆盖
//ios::app 写入的数据添加到文件的末尾
//D:\学习资料\C++\自编程序\学生信息管理系统\学生信息管理系统
if (!outfile)
{
cerr << "open error!" << endl;//cerr 把错误信息输出到控制台
exit(1);
}
while (p != NULL)
{
outfile << "学号:" << p->sID << " " << "姓名:" << p->sName << endl;
p = p->next;
}
outfile.close();
}
student *LinkQueue::DeQueue(int num)//num得小于链表的有效元素的长度
{
student *p1,*p2,*p3;
int count=1;
p1 = front;
if (num == 1)//删除头指针
{
p1 = front->next;
front = p1;
}
else
{
while (count < num-1)
{
p1 = p1->next;
count++;
}
p2 = p1;
p3 = p1;
p3 = p1->next;//p3指向待删除的元素
p1 = p3->next;
p3->next = NULL;
p2->next = p1;
}
return front;
}
student *LinkQueue::addQueue(int num)
{
student *p1, *p2,*p3;
p2 = new student;
int count = 1;
p1 = front;
cout << "please input the new sID and sName:" << endl;
cin >> p2->sID >> p2->sName;
if (num == 0)
{
front = p2;
p2->next = p1;
}
else
{
while (count < num)
{
p1 = p1->next;
count++;
}
p3 = p1->next;
p1->next = p2;
p2->next = p3;
}
return front;
}
student *LinkQueue::OrderQueue()//单向链表的排序
{
student *p1,*p2,*p3;
p3 = new student;
p1 = front;
p2 = p1->next;
for (; p1->next != NULL;p1=p1->next)
{
for (p2 = p1->next; p2 != NULL; p2 = p2->next)
{
if (p2->sID < p1->sID)
{
p3->sID = p2->sID;
p3->sName = p2->sName;
p2->sID = p1->sID;
p2->sName = p1->sName;
p1->sID = p3->sID;
p1->sName = p3->sName;
}
}
}
delete p3;
return front;
}
单向动态链表的建立、插入、删除、排序和保存
最新推荐文章于 2024-04-30 15:10:46 发布