如何建立一个存放学生信息的结构体链表

25 篇文章 0 订阅

 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;
	
}

 


 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值