单链表的应用

学生入校离校统计

#include <iostream>
using namespace std;
class Student
{
public:
	Student(char* pName);//构造函数
	~Student();//析构函数
	static Student* findname(char* pName);//静态成员函数,查找链中所有对象,查看有没有指定学生,返回Student类指针
	static int getallStudent();
	char* getName();
protected:
private:
	static Student* head;
	Student* next;
	static int allStudent;
	char name[40];
};

Student* Student::head = 0;
int Student::allStudent = 0;

int Student::getallStudent()
{
	return allStudent;
}

char* Student::getName()
{
	return name;
}

Student::Student(char* pName)
{
	strcpy(name,pName);
	name[sizeof(name)-1] = '\0';
	next = head;
	allStudent++;
	head = this;//新创建的对象变成链表头
	cout<<name<<"入学。"<<endl;
}

Student::~Student()
{
	if (head == this)//链表头是要删除的对象吗
	{
		head = next;//链表头是要删除的对象
		cout<<name<<"离校。"<<endl;
		allStudent--;
		return;
	}
	for (Student* p = head;p;p = p->next)//链表头不是要查找的对象,逐个查找。
	{
		if (p->next == this)//找到要删除的对象
		{
			p->next = next;
			cout<<name<<"离校。"<<endl;
			next = head;
			allStudent--;
			return;
		}
	}
	allStudent--;
	cout<<allStudent<<"离校。"<<endl;
}

Student* Student::findname(char* pName)
{
	for (Student* p = head;p;p = p->next)
	{
		if (strcmp(p->name,pName) == 0)
		return p;
	}
	return NULL;
}

int main()
{

	Student* p = new Student("Randy");
	cout<<"共有"<<p->getallStudent()<<"个对象。"<<endl;
	Student* p1 = new Student("Jean");
	cout<<"共有"<<p1->getallStudent()<<"个对象。"<<endl;
	Student* p2 = new Student("Kinsey");
	cout<<"共有"<<p2->getallStudent()<<"个对象。"<<endl;
	delete p;
	Student* p3 = new Student("Rose");
	cout<<"共有"<<p3->getallStudent()<<"个对象。"<<endl;
	Student* p4 = new Student("John");
	cout<<"共有"<<p4->getallStudent()<<"个对象。"<<endl;
	Student* f = Student::findname("Rose");
	if (f)
	cout<<f->getName()<<"找到了。"<<endl;
	else
	cout<<"未找到。"<<endl;
	system("pause");
	return 0;
}
结果显示:



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值