You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现生成0-50随机数直到命中49后输出的C语言链表

C语言随机数链表实现方案

原代码存在的问题

  • 仅生成了1个链表节点就退出,缺少循环生成随机数、插入链表的核心逻辑
  • 随机数范围错误:rand()%50 +1 生成的是150区间的数值,若要实现050范围需要修改为rand()%51
  • 函数声明与实际定义不匹配:printList函数声明没有参数,实际定义需要传入链表头指针,会引发编译警告

核心实现逻辑

  • 初始化链表头指针为NULL,避免首个随机数就是49的场景下出现无效节点
  • 进入永久循环,每次生成指定范围的随机数
  • 随机数等于49时,直接打印当前全链表内容后退出程序
  • 随机数不等于49时,创建新节点存储数值,插入到链表尾部后继续循环

完整可运行代码

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

struct Node {
    int data;
    struct Node* next;
};
// 修正函数声明,匹配定义的参数
void printList(struct Node* n);

int main() {
    srand(time(0)); 
    struct Node* head = NULL;
    struct Node* tail = NULL; // 存储尾指针,避免每次插入遍历全链表

    while(1) {
        // 生成0~50的随机数,如需1~50可改回rand()%50 +1
        int x = rand() % 51;
        // 碰到49直接打印链表退出
        if(x == 49) {
            printf("生成到49,当前链表内容:\n");
            printList(head);
            printf("\n");
            // 释放链表内存,避免内存泄漏
            struct Node* temp;
            while(head != NULL) {
                temp = head;
                head = head->next;
                free(temp);
            }
            return 0;
        }
        // 创建新节点
        struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
        newNode->data = x;
        newNode->next = NULL;
        // 插入链表
        if(head == NULL) {
            head = newNode;
            tail = newNode;
        } else {
            tail->next = newNode;
            tail = newNode;
        }
    }
    return 0;
}

void printList (struct Node* n){
    while (n != NULL){
        printf(" %d ", n->data);
        n = n->next;
    }
}

代码说明

  • 新增尾指针优化插入效率,插入节点的时间复杂度为O(1)
  • 新增退出前的内存释放逻辑,避免内存泄漏
  • 兼容首个随机数就是49的场景,此时会输出空链表内容

内容的提问来源于stack exchange,提问作者billyplantin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 07:09:03