C++中如何对单向链表操作

*/
 * Copyright (c) 2016,烟台大学计算机与控制工程学院
 * All rights reserved.
 * 文件名:text.cpp
 * 作者:常轩
 * 微信公众号:Worldhello
 * 完成日期:2016年6月25日
 * 版本号:V1.0
 * 问题描述:对单向链表的增加,删除,插入
 * 程序输入:无
 * 程序输出:见运行结果
 */

#include "stdio.h"
#include "stdlib.h"
#include "string.h"

struct  STUDENT{

		char name[32];
		struct  STUDENT *next;
};
void addStudent(STUDENT *stu);
void delStudent(char *name);
void saveStuToFile();
STUDENT *gStu=NULL;
int main()
{

   int i;
   for(i=0;i<100;i++)
   {
		STUDENT *stu;
		stu = (STUDENT *)malloc(sizeof(STUDENT));
		memset(stu->name,0,sizeof(stu->name));
		sprintf(stu->name,"%s%d","zhangsan",i+1);
		addStudent(stu);
   }
   saveStuToFile();
   STUDENT *p;
   p = gStu;
   while(p)
   {
	  printf("%s\n",p->name);
	  p= p->next;
   }

   for(i=20;i<30;i++)
   {
	   char name[32];
	   sprintf(name,"%s%d","zhangsan",i+1);
	    delStudent(name);
   }

   p = gStu;
   while(p)
   {
	   printf("%s\n",p->name);
	   p= p->next;
   }


}


void addStudent(STUDENT *stu)
{

	STUDENT *p;
	if(gStu==NULL)
	{
		gStu =stu;
		stu->next=NULL;
	}
	else
	{
		p = gStu;
		while(p)
		{
			if(p->next==NULL)
			{
				p->next =stu;
				stu->next =NULL;

			}
			p= p->next;

		}

	}
}
void delStudent(char *name)
{
	STUDENT *p,*pre;
	if (gStu==NULL)
	{
		return;
	}
	p =pre=gStu;
	while(p)
	{

		if (!strcmp(p->name,name))
		{
			if(p==gStu)
			{
					gStu = gStu->next;
					free(p);
					p=NULL;
			}
			else
			{
				pre->next =p->next;
				free(p);
				p=NULL;

			}
		}
		else
		{
			pre =p;
			p= p->next;
		}
	}
}

void saveStuToFile()
{
	FILE *fp;

	int filelen;

	fp = fopen("yyy.txt","w");


	STUDENT *p;
	p = gStu;
	while(p)
	{
		fwrite(p->name,32,1,fp);
		p= p->next;

	}

	fclose(fp);
}

posted @ 2016-06-26 10:56  壹言  阅读(170)  评论(0编辑  收藏  举报