C语言创建动态链表

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>

#define LEN sizeof(struct Student)

struct Student *create();
void print(struct Student *head);

struct Student{
    int num;
    float score;
    struct Student *next;
};

int n;

void main(){
    struct Student *stu;
    stu=create();
    print(stu);
    printf("\n\n");
    system("pause");


}

struct Student *create(){
    struct Student *head;
    struct Student *p1,*p2;
    p1=p2=(struct Student *) malloc(LEN);
    printf("Please enter the num:");
    scanf("%d",&p1->num);
    printf("Please enter the score");
    scanf("%f",&p1->score);
    head=NULL;
    n=0;
    while (p1->num!=0)
    {
        n++;
        if(n==1){
            head = p1;
        }else{
            p2->next=p1;
        }
            p2=p1;
            p1=(struct Student *)malloc(LEN);
            printf("\nPlease enter the num");
            scanf("%d",&p1->num);
            printf("Please enter the score");;
            scanf("%f",&p1->score);


    }
    p2->next=NULL;
    return head;

}


void print(struct Student *head){
    struct Student *p;
    printf("\nTher are %d records!\n\n",n);
    p=head;
    if(head){
        do{
            printf("学号为%d的成绩是:%f",p->num,p->score);
            p=p->next;
        }while(p);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是用C语言创建一个有序链表的示例代码: ```c #include <stdio.h> #include <stdlib.h> // 定义链表节点结构体 struct ListNode { int val; struct ListNode* next; }; // 插入元素到有序链表中 struct ListNode* insert(struct ListNode* head, int val) { // 创建新节点 struct ListNode* new_node = (struct ListNode*)malloc(sizeof(struct ListNode)); new_node->val = val; new_node->next = NULL; if (head == NULL) { // 如果链表为空,则直接插入新节点 head = new_node; } else if (head->val > val) { // 如果新节点的值小于链表头结点的值,则将新节点作为新的头结点 new_node->next = head; head = new_node; } else { // 遍历链表,找到合适的插入位置 struct ListNode* cur = head; while (cur->next && cur->next->val < val) { cur = cur->next; } new_node->next = cur->next; cur->next = new_node; } return head; } // 打印链表 void print_list(struct ListNode* head) { struct ListNode* cur = head; while (cur) { printf("%d ", cur->val); cur = cur->next; } printf("\n"); } int main() { struct ListNode* head = NULL; // 插入元素到有序链表中 head = insert(head, 5); head = insert(head, 3); head = insert(head, 7); head = insert(head, 1); head = insert(head, 9); // 打印有序链表 print_list(head); return 0; } ``` 这个示例代码中,我们定义了一个链表节点结构体 `ListNode`,包含了一个 `val` 域和一个指向下一个节点的指针 `next`。然后实现了一个 `insert` 函数,用于将一个新的元素插入到有序链表中。当链表为空时,直接插入新节点;当新节点的值小于链表头结点的值时,将新节点作为新的头结点;否则,遍历链表找到合适的插入位置。最后,我们用 `print_list` 函数打印出整个有序链表

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值