首页 > 解决方案 > 如何从原始堆栈复制堆栈

问题描述

我尝试编写 ac 程序,该程序将具有返回给定堆栈的重复堆栈的函数。复制堆栈包含与原始堆栈相同的元素,并且顺序相同。原始堆栈必须保持不变。但是我没有得到想要的输出。运行代码时没有显示最后两个 printf() 输出。代码在 printf() 命令的末尾终止,该命令显示输入堆栈的峰值元素。

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);
    }
 }
  void 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));
 }

标签: cstack

解决方案


似乎原型push/pop如下。

void push (stack *, int);
void pop (stack *);

在这种情况下,您有未定义的行为。

    n = pop(&s);
    push(&s,n);
    push(&s1,n);

上面的DuplicateStackfunction 调用实际上是传递stack **push/popfunction 而不是stack *. 既然s和都s1已经stack *,给你了。&s&s1stack **

尝试将它们更改为。

void DuplicateStack(stack *s, stack *s1){
    int n;
    stack s3;
    CreateStack(&s3);
    while(!isEmpty(s)){
        n = pop(s);  // <<<-- &s to s
        push(&s3,n);
    }
    while(!isEmpty(&s3)){
        n = pop(&s3);
        push(s,n);   // <<<--- &s to s
        push(s1,n);  // <<<----&s1 to s1
    }
 }

推荐阅读