注意注释
1、首先明确类中的成员变量和成员函数
#ifndef _STUDENT_H
#define _STUDENT_H
class Student
{
private:
char m_name[20]; //学生的名字
int m_age; //学生年龄
char m_sex; //学生性别
Student *next; //在类中定义一个结构指针
public:
Student(char *n = "xxx",int a = 20,char s = 'm'); //构造函数 初始化信息
void print(); //输出信息
void SetNext(Student *s); //设置结点
Student *GetNext(); //指向下个结点
};
#endif
2、根据类中的数据来编写成员函数
Student::Student(char *n,int a,char s)
{
cout<< "Student constructor" <<endl;
strcpy (m_name , n);
m_age = a;
m_sex = s;
next = NULL;
}
void Student::print() //输出信息
{
cout<< m_name << " " << m_age << " " << m_sex <<endl;
}
void Student::SetNext(Student *s) //设置下个结点
{
next = s;
}
Student *Student::GetNext() //移动到下个结点
{
return next;
}
3、以上都是围绕Student来写,接下来需要明确链表的作用。
#ifndef _MYLIST_H
#define _MYLIST_H
#include "Student.h"
class MyList
{
private:
Student *m_first; //在类中定义一个头指针
public:
MyList(); //构造函数初始化一个链表
void push_back(Student *s); //在后面插入学生信息
void deletelist(Student *s); //删除学生信息
void traverse(); //指针向后移动,逐个输出信息
};
#endif
4、再次根据类中的数据来编写成员函数
MyList::MyList() //初始化 头指针指向新结点
{
m_first = new Student;
}
void MyList::push_back(Student *s) //从后面插入学生数据
{
Student *p = m_first; //定义一个指针指向头结点
while ( p->GetNext() != NULL)
{
p = p -> GetNext(); //指针向后移
}
p->SetNext(s); //设置下个结点
}
void MyList::deletelist(Student *s) //删除数据
{
Student *p = m_first;
while( p->GetNext() != NULL)
{
if( p->GetNext() == s ) //当指向的结点 == 待删除的结点时
{
Student *tmp = s;
*( p->GetNext() ) = *( tmp->GetNext() ); //将指针指向待删除结点的下个结点
}
//else
p = p->GetNext(); //不能加else 否则无法指向下个结点 无法进行下去
}
}
void MyList::traverse()
{
Student *p = m_first -> GetNext(); //指向有数据的结点
while(p != NULL)
{
p->print(); //输出有数据的结点中的数据
p = p->GetNext(); //依次指向下个结点
}
}
5、最后,编写mian函数,调用成员函数
int main()
{
MyList mylist;
Student *s1 = new Student("aa" , 20 , 'm'); //开辟结点 存放数据
Student *s2 = new Student("bb" , 21 , 'w');
Student *s3 = new Student("cc" , 22 , 'm');
mylist.push_back(s1); //插入数据
mylist.push_back(s2);
mylist.push_back(s3);
mylist.traverse(); //输出
cout<< "------------------" <<endl;
mylist.deletelist(s2); //删除s2的数据
mylist.traverse(); //再次输出 进行对比
return 0;
}
6、运行结果如下:
aa 20 m
bb 21 w
cc 22 m
------------------
aa 20 m
cc 22 m