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

C++链表实现栈弹出素数相乘回推后显示为空问题求助

问题原因

你代码的核心错误集中在Pop函数的逻辑设计,以及主函数的调用逻辑和需求不匹配:

  1. Pop函数功能完全不符合需求:你要求的是先弹出所有栈内元素,计算乘积后再将结果推回栈,但你当前的Pop每调用一次就会直接访问栈顶后两个节点算乘积、插入新节点再删除旧栈顶,完全违背了栈的基本弹出逻辑,也不符合你的功能流程要求。
  2. 空指针访问风险:你在Pop中直接访问res->next->next,没有做栈长度校验,当栈内元素不足3个时会直接触发内存访问错误,程序崩溃无输出。
  3. 内存操作不匹配:你的节点是通过new申请的,却用free释放,会导致内存泄漏甚至未定义行为,应该用delete释放节点。
  4. 主函数调用逻辑错误:你调用了3次Pop,第一次调用后栈内节点结构已经被打乱,后续两次调用大概率会触发空指针访问,程序提前终止,所以最终没有输出。

解决思路

  1. 拆分功能:保留Pop函数的单一职责,仅实现弹出栈顶元素并返回值的功能;单独编写calc_product_push_back函数完成「弹出所有元素算乘积再推回栈」的需求。
  2. 增加边界校验:所有操作前先判断栈是否为空、节点数是否符合要求。
  3. 修正内存释放逻辑:用delete释放new申请的节点。

修改后可运行代码

#include <iostream>
using namespace std;

struct Node{
    int data;
    Node *next;
};
    
bool isEmpty(Node *head){
    return head == NULL;
}

// 函数名调整为isPrime更贴合实际功能
bool isPrime(Node* current,int i=2){
    if(current->data == 2) return true;
    if(current->data == 1) return false;
    if(current->data % i == 0) return false;
    if(i*i > current->data) return true;
    return isPrime(current,i+1);
}

void Push(Node *&head,int number){
    Node *temp = new Node;
    temp->data = number;
    if(isPrime(temp,2) == true){
        temp->next = head;
        head=temp;
    } else {
        cout<<"Your input is not Primenumber" << endl;
        delete temp; // 不符合素数要求的节点要释放,避免内存泄漏
    }
}

void Insert(Node *&head,int number){
    Node *temp = new Node;
    temp->data = number;
    temp->next = head;
    head=temp;
}

// 修正Pop功能:仅弹出栈顶,返回栈顶值
int Pop(Node *&head){
    if(isEmpty(head)) {
        cout << "栈已空,无法弹出" << endl;
        return -1;
    }
    Node *temp = head;
    int val = temp->data;
    head = head->next;
    delete temp;
    return val;
}

// 新增功能函数:弹出所有元素算乘积再推回
void calc_product_push_back(Node *&head) {
    if(isEmpty(head)) return;
    int product = 1;
    // 弹出所有元素计算乘积
    while(!isEmpty(head)) {
        product *= Pop(head);
    }
    // 将乘积推回栈
    Insert(head, product);
}

void display(Node *current){
    if(current==NULL){
        cout<<"Your List is NULL";
    } else {
        while(current!=NULL){
            cout<<current->data<<" ";
            current= current->next;      
        }
    }
}

int main(){
    Node *head = NULL;
    int T=3;
    for(int i=0;i<T;i++){
        int number;
        cin>>number;
        Push(head,number);
    }
    cout << "入栈后栈内容:";
    display(head);
    cout << endl;
    // 不需要调用三次Pop,直接调用功能函数即可
    calc_product_push_back(head);
    cout << "处理后栈内容:";
    display(head);  
    return 0;
}

运行示例

输入2 3 5后,输出为:

入栈后栈内容:5 3 2 
处理后栈内容:30 

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 00:45:09