简单链表操作

新建控制台应用程序,然后添加如下代码

#include <iostream.h>


struct tSTUDENT
{
	char name[20];
	bool sex;
	int  number;
	int score;
	tSTUDENT* next;
};

tSTUDENT* g_pFirst = NULL;

void ListInit()
{
	
}

void ListDestroy()
{
	tSTUDENT* p = NULL;
	tSTUDENT* q = NULL;
	if(g_pFirst)
	{
		p = g_pFirst;
		while(p)
		{
			q = p->next;
			delete p;
			p = q;
		}
		g_pFirst = NULL;
	}
}

void ListClear()
{
	tSTUDENT* p = NULL;
	tSTUDENT* q = NULL;
	if(g_pFirst)
	{
		p = g_pFirst;
		while(p)
		{
			q = p->next;
			delete p;
			p = q;
		}
		g_pFirst = NULL;
	}
}

int ListLength()
{
	int count = 0;
		
	tSTUDENT* p = NULL;
	tSTUDENT* q = NULL;
	if(g_pFirst)
	{
		p = g_pFirst;
		while(p)
		{	
			count++;
			q = p->next;
			p = q;
		}
	}
	return count;
}

tSTUDENT*  GetElem(int num)
{
	tSTUDENT* p = NULL;
	tSTUDENT* q = NULL;
	if(g_pFirst)
	{
		p = g_pFirst;
		while(p)
		{	
			if(num == p->number)
			{
				return p;
			}
			q = p->next;
			p = q;
		}
	}
	return NULL;
}

void ListInsert(char* pName,bool sex,int number,int score)
{
	tSTUDENT* p = NULL;
	tSTUDENT* q = NULL;
	tSTUDENT* r = NULL;

	p = new tSTUDENT;
	for(int i=0;i<20;i++)
	{
		p->name[i] = pName[i];
	}
	p->sex = sex;
	p->number = number;
	p->score = score;
	p->next = NULL;


	if(g_pFirst)
	{
		q = g_pFirst;
		while(q->next)
		{	
			q = q->next;
		}

		q->next = p;
	}
	else
	{
		g_pFirst = p;
	}
}

void ListDelete(int num)
{
	tSTUDENT* p = NULL;
	tSTUDENT* q = NULL;
	if(g_pFirst)
	{
		p = g_pFirst;
		if(num == p->number)
		{
			g_pFirst = p->next;
			delete p;
			return;
		}
		else
		{
			while(p)
			{	
				if(p->next)
				{
					if(num == p->next->number)
					{
						q = p->next;
						p->next = q->next;
						delete q;
						return;						
					}
				}
				p = p->next;
			}
		}
	}
}

void ListVisit()
{
	tSTUDENT* p = NULL;
	tSTUDENT* q = NULL;
	if(g_pFirst)
	{
		p = g_pFirst;
		while(p)
		{	
			cout<<"Name :"<< p->name<<endl;
			cout<<"sex "<<p->sex<<endl;
			cout<<"Number :"<<p->number<<endl;
			cout<<"score:"<<p->score<<endl;
			cout<<"---------------"<<endl;
			q = p->next;
			p = q;
		}
	}
}


void main()
{
	char name[20];
	int sex;
	int  score;
	int  num;


	cout<<"please input students' information ..."<<endl;
	for(int i=0;i<3;i++)
	{
		cout<<"Input the name:";
		cin>>name;
		cout<<"Input the sex:";
		cin>>sex;
		cout<<"Input the score:";
		cin>>score;
		cout<<"Input the number:";
		cin>>num;
		ListInsert(name,bool(sex),num,score);
	}

	ListVisit();

	ListDestroy();
}


运行效果如下


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值