C语言练习——Day11

本文提供了一个C语言实现的链表操作示例,包括创建链表、插入节点、删除指定节点的功能。代码中定义了结构体`struct Student`用于存储数据,并通过`create`函数创建链表,`del`函数删除节点,`insert`函数插入节点,最后`print`函数打印链表内容。在`main`函数中展示了这些操作的实际应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}

运行结果:在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老板来根肠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值