c - 如何从原始堆栈复制堆栈
问题描述
我尝试编写 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));
}
解决方案
似乎原型push/pop
如下。
void push (stack *, int);
void pop (stack *);
在这种情况下,您有未定义的行为。
n = pop(&s);
push(&s,n);
push(&s1,n);
上面的DuplicateStack
function 调用实际上是传递stack **
给push/pop
function 而不是stack *
. 既然s
和都s1
已经stack *
,给你了。&s
&s1
stack **
尝试将它们更改为。
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
}
}
推荐阅读
- jenkins - 如何在 Jenkins 声明式语法中捕获 POST 内容参数?
- c++ - 全屏应用程序运行时获取屏幕位图
- javascript - 您如何模仿 Chrome 扩展程序中的击键?
- matlab - 从 Julia 运行 matlab 函数
- php - 数据仍然保留,不会从零重新开始
- nestjs - NestJS gRPC 中间件
- android - 从 android 处理程序返回值
- triggers - 问题理解 Salesforce Apex 触发器在内联 SOQL 中的相等性检查
- ethereum - 什么是为以太坊构建去中心化应用程序的起点/模板
- react-native - 世博会图像很慢而且性能不好但是为什么