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

如何复制栈?C语言栈复制函数程序异常求助

问题分析与修复方案

我一眼就看到了导致程序崩溃的核心问题,同时也帮你梳理了整个逻辑的正确性:

核心错误:指针类型不匹配导致程序崩溃

在你的DuplicateStack函数里,调用pop(&s)是完全错误的——s本身已经是stack*类型的指针了,但你却传递了它的地址(也就是stack**类型)给pop函数。pop函数预期接收的是stack*,这种类型不匹配会直接触发内存访问错误,程序在执行到这一步时就崩溃了,所以后面的两个printf语句根本没机会执行。

修复后的DuplicateStack函数

我已经修正了这个错误,同时确保原栈能完全恢复,复制栈的顺序和原栈一致:

void DuplicateStack(stack *s, stack *s1) {
    int n;
    stack s3;
    CreateStack(&s3);

    // 将原栈元素转移到临时栈,此时原栈为空
    while (!isEmpty(s)) {
        n = pop(s);  // 修正为传递s(stack*),而不是&s(stack**)
        push(&s3, n);
    }

    // 从临时栈弹出元素,同时恢复原栈和复制到目标栈
    while (!isEmpty(&s3)) {
        n = pop(&s3);
        push(s, n);    // 把元素放回原栈,恢复原有顺序
        push(s1, n);   // 把元素推入复制栈,保证顺序和原栈一致
    }
}

额外的优化建议

  • 规范main函数写法:void main()不符合C语言标准,建议改成int main(),并在函数末尾加上return 0;,保证程序的可移植性。
  • 检查辅助函数的正确性:确保你的CreateStack、isEmpty、pop、push、peek这些栈操作函数实现正确,比如pop要正确释放节点内存,peek要先判断栈是否为空,这些辅助函数的bug也可能导致奇怪的问题。

完整可运行代码示例

这里我补充了常见的链表实现栈的辅助函数,你可以直接运行测试:

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

// 链表节点定义
typedef struct Node {
    int data;
    struct Node* next;
} Node;

// 栈结构体定义
typedef struct stack {
    Node* top;
} stack;

// 初始化栈
void CreateStack(stack *s) {
    s->top = NULL;
}

// 判断栈是否为空
int isEmpty(stack *s) {
    return s->top == NULL;
}

// 入栈操作
void push(stack *s, int val) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    if (!newNode) {
        printf("Memory allocation failed!\n");
        exit(1);
    }
    newNode->data = val;
    newNode->next = s->top;
    s->top = newNode;
}

// 出栈操作,返回栈顶元素
int pop(stack *s) {
    if (isEmpty(s)) {
        printf("Stack underflow!\n");
        exit(1);
    }
    Node* temp = s->top;
    int val = temp->data;
    s->top = s->top->next;
    free(temp);
    return val;
}

// 获取栈顶元素
int peek(stack *s) {
    if (isEmpty(s)) {
        printf("Stack is empty!\n");
        exit(1);
    }
    return s->top->data;
}

// 复制栈函数(已修复)
void DuplicateStack(stack *s, stack *s1) {
    int n;
    stack s3;
    CreateStack(&s3);

    while (!isEmpty(s)) {
        n = pop(s);
        push(&s3, n);
    }

    while (!isEmpty(&s3)) {
        n = pop(&s3);
        push(s, n);
        push(s1, n);
    }
}

int main() {
    stack s, s1;
    CreateStack(&s);
    CreateStack(&s1);
    int num, n;

    printf("Enter no.of numbers you want to enter: ");
    scanf("%d", &num);

    for (int i = 0; i < num; i++) {
        scanf("%d", &n);
        push(&s, n);
    }

    printf("Top element: %d\n", peek(&s));
    DuplicateStack(&s, &s1);
    printf("Top Element in the Original Stack: %d\n", peek(&s));
    printf("Top Element in the Duplicate Stack: %d\n", peek(&s1));

    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:26:32