链表建立、查找、增加、删除 -录入学生成绩举例

typedef struct student
{
    char name[15];
int mark;
struct student *next;
}Node, *node;


int Search(char *name, node head)
{
    node p;
p=head->next;
while(p!=NULL)
{
        if(strcmp(name,p->name)==0)
        {
            printf("Search Mark is %d\n",p->mark);
return p->mark;
}
else
{
           p=p->next;
}
}
printf("Search Empty\n");
return C_SYS_ERR;

}


node Del(char *name, node head)
{
    node p,q;
p = head;
while(p->next != NULL)
{
if(strcmp(name,p->next->name)==0)
   {   
      q = p->next;
  p->next = p->next->next;
  free(q); /*一定要释放*/
  return head;
}
else
{
p=p->next;
}
}


return NULL;
}


node Add(char *name, node head)
{
    node p, newnode;
newnode =(node) malloc(sizeof(Node));
if(newnode==NULL)
{
        printf("Error3 \n");
exit(1);
}
else
{
        printf("Input The Add name :");
scanf("%s", &newnode->name);
printf("Input The Add mark :");
scanf("%d", &newnode->mark);
}


p = head->next;
while(p!=NULL)
{
if(strcmp(name,p->name)==0)
        {
            newnode->next = p->next;
            p->next=newnode;   
            return head;
        }
        else
        {
            p=p->next;
        }


}
return NULL;


}
void Print(node head)
{
    node p;
p = head->next;
printf("Name    Mark\n");
    while(p!=NULL)
    {
        printf("%s    %d\n",p->name, p->mark);
p=p->next;
}
}




int main(int argc , char* argv[])
{
    int num,i,j;
char name[15];
node p, p1, head;
head = (node) malloc(sizeof(Node));
if(head==NULL)
{
        printf("Error1!\n");
return C_SYS_ERR;
}
else
   head->next=NULL;
printf("Input number of students:");
scanf("%d",&num);
printf("Input the information:");
for(i=0; i<num; i++)
{
        p=(node)malloc(sizeof(Node));
if(p==NULL)
{
            printf("Error2!\n");
return 0;
}
else
{
            printf("\nname:");
scanf("%s",&p->name);
printf("mark:");
scanf("%d",&p->mark);
if(head->next == NULL)
{
                head->next = p;
p1=p;
}
else
{
                p1->next = p;
p1 = p; 
}
}
}


p1->next =NULL;
Print(head);




printf("please input the name while do you want to Search \n");
scanf("%s", name);
Search(name, head);


printf("please input the name while do you want to Del \n");
scanf("%s", name);
Del(name, head);
Print(head);


printf("please input the name where do you want to Add \n");
scanf("%s", name);
Add(name, head);
Print(head);
system("PAUSE");
return 0;
}


猜你喜欢

转载自blog.csdn.net/shayne_lee/article/details/80329987