#include <stdio.h>
#include <stdlib.h>
#define LEN sizeof(struct student)
struct student
{
char name[10];
int age;
struct student *next;
};
struct student *head = NULL;
void Create_list()
{
struct student *p1,*p2;
p2 = head;
p1 = (struct student*)malloc(LEN);
printf("Please input name and age such as (aa 1)\n");
scanf("%s %d",p1 -> name,&p1 -> age);
if(NULL == head)
{
head = p1;
p1 -> next = NULL;
}
else
{
while(p2 -> next)
{
p2 = p2 -> next;
}
p2 -> next = p1;
p1 -> next = NULL;
}
}
void printlist()
{
struct student *p = head;
while(p)
{
printf("name = %s,age = %d\n",p -> name,p -> age);
p = p -> next;
}
}
void Add_list()
{
struct student *p1,*p2;
p2 = head;
p1 = (struct student*)malloc(LEN);
printf("Please input name and age such as (aa 1)\n");
scanf("%s %d",p1 -> name,&p1 -> age);
while(p2 -> next)
{
p2 = p2 -> next;
}
p2 -> next = p1;
p1 -> next = NULL;
}
void Del_list()
{
struct student *p1,*p2;
char name[10];
p2 = head;
p1 = p2 -> next;
printf("Please input del name:");
scanf("%s",name);
while(p2)
{
if(strcmp(p2 -> name,name) == 0 && p2 == head)
{
head = p1;
p2 -> next = NULL;
break;
}
else if(strcmp(p1 -> name,name) == 0)
{
p2 -> next = p1 -> next;
p1 -> next = NULL;
break;
}
else if(p1 -> next == NULL)
{
printf("can not find name to del\n");
break;
}
else
{
p2 = p2 -> next;
p1 = p2 -> next;
}
}
}
void Update_list()
{
struct student *p = head;
char name[10];
int age;
printf("Please input name:");
scanf("%s",name);
printf("Please input age you want to update:");
scanf("%d",&age);
while(p)
{
if(strcmp(p -> name,name) == 0)
{
p -> age = age;
break;
}
p = p -> next;
}
if(p == NULL)
{
printf("can not find name to update!\n");
}
}
int main()
{
printf("Please input num:");
int i,n;
printf("1.Create 2.Add 3.Del 4.Update 5.Print 6.Exit\n");
while(1)
{
printf("Please input num:");
scanf("%d",&n);
switch(n)
{
case 1:Create_list();break;
case 2:Add_list();break;
case 3:Del_list();break;
case 4:Update_list();break;
case 5:printlist();break;
}
if(n == 6)
break;
}
}
不带头结点的链表的增删改查
最新推荐文章于 2025-03-31 11:23:46 发布