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

如何在C语言链式栈中实现Peek操作?

实现栈的Peek操作

1. 完善peek函数

Peek操作的核心是查看栈顶元素但不修改栈结构,实现代码如下:

struct info *peek(struct info *top){
    // 判断栈是否为空
    if(top == NULL){
        printf("栈为空,没有元素可查看\n");
    } else {
        // 按照指定格式打印栈顶学生信息
        printf("The topmost ID number is: %d\n", top->idnum);
        printf("The topmost Name is: %s\n", top->name);
        printf("The topmost Course is: %s\n", top->courses);
    }
    // Peek不修改栈,直接返回原栈顶指针
    return top;
}

2. 在主函数中调用Peek操作

在main函数的switch语句case 3分支中添加调用逻辑:

case 3:
    top = peek(top);
    break;

3. 修正现有代码的bug

你的push函数存在空指针访问风险:当malloc失败返回NULL时,执行p->next = NULL会导致程序崩溃,同时scanf读取数组时无需加&(数组名本身就是指针),修改后的push函数如下:

struct info *push(struct info *top)
{
    struct info *p;
    p=(struct info *)malloc(sizeof(struct info));
    if(p==NULL)
    {
        printf("内存分配失败,无法添加学生信息\n");
        // 内存分配失败,返回原栈顶指针
        return top;
    }
    else
    {
        printf("Enter the Student name: ");
        scanf("%s",p->name);
        printf("Enter Student course: ");
        scanf("%s",p->courses);
        printf("Enter the ID number of Student: ");
        scanf("%d",&p->idnum);
        p->next=top;
        top=p;
    }
    return(top);
}

4. 测试效果

当选择选项3时,若栈不为空,会输出指定格式的栈顶信息:

The topmost ID number is: [学生ID]
The topmost Name is: [学生姓名]
The topmost Course is: [课程名称]

若栈为空,则提示"栈为空,没有元素可查看"。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 00:05:27