链表保存数据

来源:互联网 发布:上海java培训公司名单 编辑:程序博客网 时间:2024/06/08 13:16
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct stu//结构体
{
int num;
char name[20];
struct stu * next;
}pstu,*st;
st add(st temp,st *head);//链表  添加节点
void show(pstu  * head);//显示链表
void sss();
st  stu_add(st head)//添加
{
if(head==NULL)
{
head=(pstu * )malloc(sizeof(pstu));
head->next=NULL;
}
int i=0;
for(i=0;i<5;i++)
{
st temp=(pstu * )malloc(sizeof(pstu));
printf("num=");
scanf("%d",&temp->num);
printf("name=");
scanf("%s",temp->name);
temp->next=head->next;
head->next=temp;//temp=head->next;
// temp=NULL;
}
return head;
}
pstu * delete(st head)//删除
{
if(head==NULL || head->next==NULL)
{
printf("empty");
return ;
}
int i=0;
pstu *p=head->next;
pstu *q=head;
printf("输入你要删除的id");
int n;
scanf("%d",&n);
while(p!=NULL)
{
if(p->num==n)
{
q->next=p->next;
free(p);
p=NULL;
i=1;
break;//刚开始没有跳出循环,一直显示段错误
}
q=q->next;
p=p->next;
}
if(i==1)
{
printf("删除成功\n");
}
else
{
printf("没有此人\n");
}
return head;
}
void search(pstu *head)//查找
{
if(head==NULL || head->next==NULL)
{
printf("empty");
return ;
}
printf("输入要查找的id:");
int n;
scanf("%d",&n);
pstu *p;
int i=0;
p=head->next;
while(p!=NULL)
{
if(p->num==n)
{
printf("num=%d,name=%s\n",p->num,p->name);
printf("输入你的选择:");
int a;
scanf("%d",&a);
if(a==1)
{
printf("输入新的id:");
scanf("%d",&p->num);
}
i=1;
break;
}
p=p->next;
}
if(i!=1)
{
printf("查无此人");
}
}
int main()
{
pstu *head=NULL;
head=stu_add(head);


show(head);
printf("start\n");
sss();
// head=delete(head);
// show(head);
// search(head);
// show(head);
return ;
}
void sss()
{
st head=(st)malloc(sizeof(pstu));
if(head==NULL || head->next==NULL)
{
printf("file empty\n");
return ;
}
// head->next=NULL; //有毛病,直接给置空
st q;
q=head->next;
while(q!=NULL)
{
printf("num=%d,name=%s\n",q->num,q->name);
q=q->next;
// q=(st)malloc(sizeof(pstu));
}
// free(head);
// head=NULL;
}
void show(pstu *head)
{
// printf("show");
if(head==NULL || head->next==NULL)
{
printf("emppty");
// return ;
}
pstu *p;
// q=head;
p=head->next;
// printf("asd");
while(p!=NULL)
{
printf("num=%d,name=%s\n",p->num,p->name);
p=p->next;
}
}
0 0
原创粉丝点击