MyList类中使用了Student的对象作为私有变量
学生类作为一个单独的节点,有next指针,类似于一个结构体,再用MyList类建立链表,每次使用new运算符开辟一个新的结点
Student.h
#ifndef _STUDENT_H
#define _STUDENT_H
class Student
{
private:
char name[20];
int age;
char sex;
Student *next;
public:
Student(char *n="xxx", int a=20, char s='m');
void print();
void SetNext(Student *s);
Student *GetNext();
};
#endif
Student.cpp
#include "Student.h"
#include <iostream>
#include <string.h>
using namespace std;
Student::Student(char *n, int a, char s)
{
cout << "Student constructor!" << endl;
strcpy(name,n); //注意字符串要复制过去,不好直接赋值
age=a;
sex=s;
next=NULL;
}
void Student::print()
{
cout << name << " " << age << " " << sex << endl;
}
void Student::SetNext(Student *s)
{
next=s;
}
Student *Student::GetNext()
{
return next;
}
MyList.h
#ifndef _MYLIST_H
#define _MYLIST_H
#include "Student.h"
class MyList
{
private:
Student *m_first; //头结点
public:
MyList(); //构造函数初始化一个链表
void push_back(Student *s);
void traverse();
void remove(Student *s);
};
#endif
MyList.cpp
#include "MyList.h"
#include <iostream>
#include <stdlib.h>
using namespace std;
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::traverse()
{
Student *p=m_first;
while(p->GetNext()!=NULL)
{
p=p->GetNext();
p->print();
//p=p->GetNext();
}
}
void MyList::remove(Student *s)
{
Student *p=m_first;
while(p->GetNext() != NULL)
{
if(p->GetNext() == s)
{
Student *tmp = s;
p->SetNext(tmp->GetNext());
//*(p->GetNext()) = *( tmp->GetNext() ) ; 这个没有用到那个函数
delete s;
}
p=p->GetNext(); // 这一步不管是否删除了那个结点,p都要向后移动一步
}
}
main.cpp
#include "MyList.h"
#include <iostream>
using namespace std;
int main()
{
MyList myList;
Student *s1=new Student("aa",20,'m');
Student *s2=new Student("bb",21,'f');
Student *s3=new Student("cc",22,'m');
Student *s4=new Student("dd",23,'f');
Student *s5=new Student("ee",24,'m');
Student *s6=new Student("ff",25,'f');
myList.push_back(s1);
myList.push_back(s2);
myList.push_back(s3);
myList.push_back(s4);
myList.push_back(s5);
myList.push_back(s6);
myList.traverse();
cout << "*************" << endl;
myList.remove(s2);
myList.traverse();
return 0;
}