gpt4 book ai didi

c - 如何从原始堆栈复制堆栈

转载 作者:太空宇宙 更新时间:2023-11-04 01:16:08 25 4
gpt4 key购买 nike

我试图编写一个 c 程序,该程序将具有一个返回给定堆栈的重复堆栈的函数。复制堆栈包含与原始堆栈相同的元素,并且顺序相同。原始堆栈必须保持不变。但是我没有得到想要的输出。运行代码时,最后两个 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));
}

最佳答案

看来push/pop的原型(prototype)如下。

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

在那种情况下,你有未定义的行为。

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

上面在DuplicateStack 函数中的调用实际上是将stack ** 传递给push/pop 函数而不是stack *。因为 ss1 已经是 stack * ,所以 &s&s1 给你堆栈 **

尝试将它们更改为。

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
}
}

关于c - 如何从原始堆栈复制堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58625800/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com