链表的创建与删除链表中的元素

来源:互联网 发布:淘宝上传3c认证入口 编辑:程序博客网 时间:2024/05/31 19:53
#include <malloc.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define N 3
#define LEN sizeof(struct grade)
struct grade
{
char no[7];
int score;
struct grade *next;
};
struct grade *del(struct grade *head){
char num[7];
struct grade *p1;
struct grade *p2;
printf("input the del no:");
scanf("%s",num);
if(head == NULL){
printf("\n List is NULL\n");
return(head);
}
p1 = head;
while(strcmp(p1-> no,num) != 0 && p1 -> next != NULL){
p2 = p1;
p1=p1->next;
}
if(strcmp(p1 -> no,num) == 0){
if(p1 == head)
head = p1 -> next;
else
p2 ->next = p1 -> next;
free(p1);
printf("delete:%s\n",num);
}
else
printf("%s not found\n",num);
return(head);
}
struct grade *head = NULL,*new,*tail;
struct grade *create(void)
{
// struct grade *head = NULL,*new,*tail;
int i =1;
for(;i<=N;i++){
new = (struct grade*) malloc(LEN);
printf("Input the number of student No.%d(6 bytes):",i);
scanf("%s",new->no);
if(strcmp(new->no,"000000") == 0){
free(new);
break;
}
printf("Input the score of the student No. %d:",i);
scanf("%d",&new->score);
new -> next == NULL;
if(i == 1) head = new ;
else
tail -> next = new;
tail = new;
}
return head;


}


main()
{
struct grade *p;
int i;
p = create();
// del(p);
if(p != NULL)


for(i = 1;i<= N;i++){
printf("%s:%d\n",p->no,p->score);
p = p ->next;
}
p = del(head);
for(i = 1;i<= 2;i++){
                printf("%s:%d\n",p->no,p->score);
                p = p ->next;
        }       
}
原创粉丝点击