61、创建一个链表。(包括创建,插入,删除等功能)
#include <stdio.h>
#include <stdlib.h>
#define LEN sizeof(struct Student)
struct Student{
int num;
float score;
struct Student* next;//代表指针域,指向直接后继元素
};
int n;
struct Student* create(void){
struct Student *p1,*p2;
struct Student *head;
n=0;
p1=p2=(struct Student*)malloc(LEN);
printf("p1->num,p1->score:(输入p1->num=0时结束)\n");
scanf("%d%f",&p1->num,&p1->score);
head=p1;
while(p1->num!=0){
p2->next=p1;
p2=p1;
p1=(struct Student*)malloc(LEN);
scanf("%d%f",&p1->num,&p1->score);
n++;
}
p2->next=NULL;
return head;
}
struct Student* del(struct Student *head,int num){
struct Student* p1,* p2;
if (head==NULL) {
printf("这是一个空链表");
return head;
}
p1=head;
while (p1->num!=num&&p1->next!=NULL) {
p2=p1;
p1=p1->next;
}
if (p1->num==num) {
if (p1==head) {
head=p1->next;
}
else{
p2->next=p1->next;
}
printf("delete:%d",num);
}
return head;
}
void insert(struct Student *node,int num,float score){
struct Student* p1=(struct Student*)malloc(LEN);
p1->num=num;
p1->score=score;
if (node->next==NULL) {
node->next=p1;
p1->next=NULL;
}
else {
p1->next=node->next;
node->next=p1;
}
printf("插入的值为:%d %f",p1->num,p1->score);
}
void print(struct Student *head){
struct Student* p;
p=head;
if(head!=NULL){
while(p!=NULL){
printf("%d %f\n",p->num,p->score);
p=p->next;
}
}
}
int main(void) {
struct Student* create(void);
void print(struct Student *head);
void insert(struct Student *node,int num,float score);
struct Student* del(struct Student *head,int num);
struct Student* pt,* node;
pt=create();
node=pt->next;
printf("创造的链表为:");
print(pt);
insert(node,3,54);
printf("\n插入后的链表为:");
print(pt);
del(pt,3);
printf("\n删除后的链表为:");
print(pt);
return 0;
}
运行结果: