zoukankan      html  css  js  c++  java
  • 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
    ",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
    ",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);
    }
    

  • 相关阅读:
    Git是如何存储对象的
    原来自己一直平凡着 2015-10-20
    把十进制数(long型)分别以二进制和十六进制形式输出,不能使用printf系列。
    #define XXX do{...}while(0)
    函数的递归调用例子学习
    MAC OSX 下安装 CTAGS
    MAC OSX 下安装Cscope
    python画图
    python读取文件内容方法
    python变量传递给系统命令的方法
  • 原文地址:https://www.cnblogs.com/chxuan/p/8232174.html
Copyright © 2011-2022 走看看