线性表的简单实现

来源:互联网 发布:js常量定义 编辑:程序博客网 时间:2024/05/01 21:58

 

Linearlist.h:

#include
using namespace std;
const int maxLen=20;

struct Student
{
string stuName;
int stuId;
int age;
int score;
};

class List
{
private:
int listLen;
public:
bool IsEmpty() {return listLen == 1;}
bool IsFull() {return listLen == maxLen;}
void Insert(List &list, Student stud, int pos);
void Delete(List &list, int pos);
List();
Student stu[maxLen];
};


 

Liearlist.cpp:

#include "List.h"
List::List()
{
this->listLen = 1;
}
void List::Insert(List &list, Student stud, int pos)
{
if(listLen < maxLen && pos >= 0 && pos < listLen)
{
for(int i = listLen-1; i >= pos; i--)
{
stu[i+1] = stu[i];
}
stu[pos] = stud;
}
listLen++;
}

void List::Delete(List &list, int pos)
{
if(listLen > 0 && pos >= 0 && pos < listLen)
{
for(int i = pos; i < listLen; i++)
{
stu[i] = stu[i+1];
}
}
listLen--;
}

 

Testlist:

#include <iostream>
#include "List.h"
using namespace std;

int main()
{
List list;
Student student,student1,student2,student3;
student.age = 20;
student.score = 80;
student.stuId = 1;
student.stuName = "zhang";
student1.age = 21;
student1.score = 80;
student1.stuId = 1;
student1.stuName = "li";
student2.age = 22;
student2.score = 80;
student2.stuId = 1;
student2.stuName = "wang";
student3.age = 23;
student3.score = 80;
student3.stuId = 1;
student3.stuName = "zhao";
list.Insert(list, student, 0);
list.Insert(list, student2, 1);
list.Insert(list, student3, 2);
list.Insert(list, student1, 1);
list.Delete(list, 2);

cout << list.stu[0].age << " " << list.stu[1].age << " " << list.stu[2].age << " " << list.stu[3].age<< endl;

cout << list.IsFull() << " " << list.IsEmpty() << endl;

return 0;
}

原创粉丝点击