供C语言的初学者熟悉链表以及结构体,仅供参考,不足之处,敬请谅解!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stuNode{
int number;
char name[20];
int age;
struct stuNode *next;
};
struct stuNode * newChain()
{
int n,i;
struct stuNode *head, *cur, *temp;
printf("input the number of students:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
temp=(struct stuNode *)malloc(sizeof(struct stuNode));
if(temp!=NULL)
{
printf("input the number:");
scanf("%d",&temp->number);
getchar();
printf("input the name:");
gets(temp->name);
printf("input the age:");
scanf("%d",&temp->age);
temp->next=NULL;
if(i==0)
head=cur=temp;
else
{
cur->next=temp;
cur=cur->next;
}
}
}
return head;
}
int display(struct stuNode * head)
{
struct stuNode *cur;
cur=head;
while(cur!=NULL)
{
printf("%5d\t%20s\t%d\n",cur->number,cur->name,cur->age);
cur=cur->next;
}
return 0;
}
int search(struct stuNode * head)
{
struct stuNode *cur;
cur=head;
char name[20];
printf("input the name you want to search:");
getchar();
gets(name);
while(cur!=NULL)
{
if(strcmp(cur->name,name)==0)
break;
cur=cur->next;
}
if(cur==NULL)
printf("no found.\n");
else
{
printf("%5d\t%20s\t%d\n",cur->number,cur->name,cur->age);
}
return 0;
}
struct stuNode * dele(struct stuNode * head)
{
struct stuNode *cur,*temp;
cur=head;
int number;
printf("input the number u want to delete:");
scanf("%d",&number);
if(head->number==number)
{
head=head->next;
free(cur);
}
else{
while(cur->next!=NULL && cur->next->number!=number)
cur=cur->next;
if(cur->next!=NULL){
temp=cur->next;
cur->next=temp->next;
free(temp);
}
}
return head;
}
int add(struct stuNode * head)
{
struct stuNode *cur,*temp;
cur=head;
while(cur->next!=NULL)
cur=cur->next;
temp=(struct stuNode *)malloc(sizeof(struct stuNode));
if(temp!=NULL)
{
printf("input the number:");
scanf("%d",&temp->number);
getchar();
printf("input the name:");
gets(temp->name);
printf("input the age:");
scanf("%d",&temp->age);
temp->next=NULL;
cur->next=temp;
}
return 0;
}
int update(struct stuNode * head)
{
struct stuNode *cur;
int number;
cur=head;
printf("input the number of the student:");
scanf("%d",&number);
while(cur!=NULL && cur->number!=number)
cur=cur->next;
if(cur!=NULL)
{
printf("input the name of the student:");
getchar();
gets(cur->name);
printf("input the age of the student:");
scanf("%d",&cur->age);
}
return 0;
}
int main()
{
int sel;
struct stuNode *head;
while(1)
{
printf("\n\t=================\n");
printf("\t 1. new chain\n");
printf("\t 2. display chain\n");
printf("\t 3. search\n");
printf("\t 4. delete\n");
printf("\t 5. add\n");
printf("\t 6. update chain\n");
printf("\t 7. quit\n");
printf("\t input your choice:");
scanf("%d",&sel);
switch(sel)
{
case 1: head=newChain(); break;
case 2: display(head); break;
case 3: search(head); break;
case 4: head=dele(head); break;
case 5: add(head); break;
case 6: update(head); break;
case 7: return 0;
}
}
return 0;
}