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

如何用C实现保留原栈结构的栈内整数平均值计算

栈平均值计算功能整合实现

需求说明

  • 计算当前栈中所有整数的平均值
  • 计算完成后必须保持栈的原始结构不变
  • 允许使用临时数据结构辅助计算

整合后的完整代码

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

#define SIZE 5

int stack[SIZE], t;
// 临时栈用于暂存原栈元素,计算后恢复原栈结构
int temp_stack[SIZE], temp_t;

void stack_init(void);
void pop(void);
int top(void);
int empty(void);
int push(int x);
double calculate_average(void);
void temp_stack_init(void);
int temp_push(int x);
void temp_pop(void);
int temp_top(void);
int temp_empty(void);
int temp_is_full(void);

int main() {
    int i;
    int loop = 1;
    stack_init();
    temp_stack_init();
    while (loop == 1) {
        scanf("%d", &i);
        if (i == 0) {
            // 弹出栈顶元素指令
            if (empty())
                printf("Error - Stack is empty\n");
            else
                pop();
        } else if (i == -99) {
            // 新增:触发平均值计算指令
            if (empty())
                printf("Error - Stack is empty\n");
            else {
                double avg = calculate_average();
                printf("Average: %.2f\n", avg);
            }
        } else if (i < 0) {
            // 查看栈顶元素指令
            if (empty())
                printf("Error - Stack is empty\n");
            else
                printf("%d\n", top());
        } else {
            // 压入正数元素指令
            if (push(i) == 0) {
                printf("Stack is full\n");
            }
        }
    }
}

// 核心:计算栈平均值的函数
double calculate_average(void) {
    int count = 0;
    double sum = 0.0;

    // 1. 将原栈元素弹出到临时栈,同时累加求和、统计元素数量
    while (!empty()) {
        int val = top();
        pop();
        temp_push(val);
        sum += val;
        count++;
    }

    // 2. 将临时栈元素弹回原栈,恢复原始结构
    while (!temp_empty()) {
        int val = temp_top();
        temp_pop();
        push(val);
    }

    // 3. 计算并返回平均值
    return sum / count;
}

// 原栈操作辅助函数
int is_full() {
    return t == SIZE - 1;
}

void stack_init(void) {
    t = -1;
}

int push(int x) {
    if (is_full())
        return 0;
    t++;
    stack[t] = x;
    return 1;
}

void pop(void) {
    t--;
}

int top(void) {
    return stack[t];
}

int empty(void) {
    return t == -1;
}

// 临时栈操作辅助函数
int temp_is_full() {
    return temp_t == SIZE - 1;
}

void temp_stack_init(void) {
    temp_t = -1;
}

int temp_push(int x) {
    if (temp_is_full())
        return 0;
    temp_t++;
    temp_stack[temp_t] = x;
    return 1;
}

void temp_pop(void) {
    temp_t--;
}

int temp_top(void) {
    return temp_stack[temp_t];
}

int temp_empty(void) {
    return temp_t == -1;
}

关键说明

  • 触发逻辑:新增输入指令-99触发平均值计算,避免和现有指令(i=0弹出、i<0查看栈顶)冲突
  • 结构保护:通过独立的临时栈暂存原栈元素,计算完成后将元素全部回推原栈,确保原栈结构完全不变
  • 计算逻辑修正:放弃原思路中用栈满状态获取元素数量的错误方式,改为遍历过程中实时统计元素个数,保证计算准确性
  • 边界兼容:栈为空时触发计算会输出错误提示,和现有错误处理逻辑保持一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 18:45:38