在c-hw中使用数组的两个堆栈,以避免弹出时插入零? [英] two stack using array in c-hw to avoid insertion of zero while popping?
本文介绍了在c-hw中使用数组的两个堆栈,以避免弹出时插入零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在一个数组中实现两个堆栈.
两个堆栈的push
操作均有效.
但是在弹出操作中,当我从第一个堆栈中弹出一个元素时,第二个堆栈中的其余元素将向左移动,但是第二个堆栈的顶部将放置一个零.如何避免这个零?
代码如下.
有人请轻松帮助.
Hi, I am trying to implement two stacks in one array.
The push
operation of both the stacks works.
But in the popping, when i pop an element from the first stack then the remaining elements in second stack shift to left but a zero will be placed at the second stack''s top. How to avoid this zero?
The code is ginven below.
Somebody please help.
#include
#include
#define max 9
int i,stk[max]={NULL},top1=-1,top2=-1,btn1=0,btn2=0;
void display()
{
printf("\nThe stack is...\n\n");
for(i=0;i<=top2;i++)
printf("%d ",stk[i]);
}
void push_first()
{
if(top1!=max)
{
for(i=top2+1;i>=btn2;i--)
stk[i]=stk[i-1];
top2++;
btn2++;
top1++;
printf("\nEnter the element:");
scanf("%d",&stk[top1]);
}
display();
}
void push_second()
{
if(top2!=max)
{
top2++;
printf("\nEnter the element:");
scanf("%d",&stk[top2]);
}
display();
}
void pop_first()
{
if(top1!=btn1-1)
{
printf("\nPopped element :%d",stk[top1]);
for(i=btn2-1;i<top2;i++)
{
stk[i]=stk[i+1];
stk[i+1]='\0';
}
btn2--;
top1--;
}
display();
}
void pop_second()
{
if(top2!=top1)
{
printf("\nPopped element :%d",stk[top2]);
top2--;
}
display();
}
int main()
{
int ch;
clrscr();
do
{
printf("\n\n MENU");
printf("\n1.Push first\n2.Push second\n3.Pop first\n4.Pop second\n5.Display\n6.Exit");
printf("\nEnter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:push_first();
break;
case 2:push_second();
break;
case 3:pop_first();
break;
case 4:pop_second();
break;
case 5:display();break;
case 6:exit(0);
default:printf("\nInvalid choice!");
}
}while(ch!=6);
getch();
return(0);
}
推荐答案
可能更多
高效,简单和安全
放置堆栈的底部-
在数组的两端... :)
添加,LP:
正确.
在数组的底部创建一个堆栈,push将增加索引;并在数组顶部放置一个堆栈,在该堆栈中推入将减少索引.完全不需要在数组中移动数据!
It could be more
efficient, simple and secure
to place the bottoms of the stacks -
at the both ends of an array... :)
Added,LP:
correct.
create one stack at the bottom of the array, push would increment the index; and one stack at the top of the array, where push would decrement the index. No need to move data in the array at all!
只需递减top2--;
循环in pop_first()
之后:)
Just decrementtop2--;
after the loopin pop_first()
:)
这篇关于在c-hw中使用数组的两个堆栈,以避免弹出时插入零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文