用C计算堆栈中的元素数



我尝试使用for循环来获取总数。它工作得很好,但这只是第一次输出。根据下面的代码,如果选项4是您的指令,您将在第一个输出中得到正确的响应,但如果再次单击选项4,它将不断增加。我的实际问题是如何存储循环的第一个输出。

#include<stdio.h>
int top=-1,m=0;
int A[200],k,n,a,i;
void push(){
if(top>=n-1)
{
printf("ntSTACK is FULL!!n");  
}
else
{
printf("Enter the value to be pushed:");
scanf("%d",&a);
top++;
A[top]=a;
}
}
void pop(){
if(top<=-1)
{
printf("nt Stack is EMPTY!!n");
}
else
{
printf("nt The popped elements is %dn",A[top]);
top--;
}
}
int main()
{
printf("***********n");
printf("Set the size of your stack(max 200).n");
scanf("%d",&n);
printf("You've set the size of the Stack to %dn", n);
printf("nt ........................n");
printf("nt 1- Push into the stack.n");
printf("nt 2- Pop the stack.n");
printf("nt 3- Display the elements in the stack.n");
printf("nt 4- Get the number of elements in the stack.n");
printf("nt 5- EXIT.n");
printf("nt ........................n");
printf("n");
do{
printf("Enter your instruction: ");
scanf("%d",&k);

switch(k){
case 1:
push();
printf("n");
break;
case 2:
pop();
printf("n");
break;
case 3:
if(top>=0){
printf("nt Your Stack n");
for(i=top;i>=0;i--){
printf("nt %dn",A[i]);
}
printf("n");
}
else{
printf("Stack is EMPTY!!");
}
break;
case 4:
for(i=0;i<=top;i++){
if(A[i] != top)
m++;
}
printf("%d",m);
printf("n");
break;
case 5:
printf("nt EXITTED...");
break;
default:
printf("nt Not in the above instruction.nn");
}
}
while(k!=5);
return 0;
}

要显示给定时间的元素计数,只需显示top+1的值。

#include<stdio.h>
int top=-1;
int A[200],k,n,a,i;
void push(){
if(top>=n-1)
{
printf("ntSTACK is FULL!!n");  
}
else
{
printf("Enter the value to be pushed:");
scanf("%d",&a);
top++;
A[top]=a;
}
}
void pop(){
if(top<=-1)
{
printf("nt Stack is EMPTY!!n");
}
else
{
printf("nt The popped elements is %dn",A[top]);
top--;
}
}
int main()
{
printf("***********n");
printf("Set the size of your stack(max 200).n");
scanf("%d",&n);
printf("You've set the size of the Stack to %dn", n);
printf("nt ........................n");
printf("nt 1- Push into the stack.n");
printf("nt 2- Pop the stack.n");
printf("nt 3- Display the elements in the stack.n");
printf("nt 4- Get the number of elements in the stack.n");
printf("nt 5- EXIT.n");
printf("nt ........................n");
printf("n");
do{
printf("Enter your instruction: ");
scanf("%d",&k);

switch(k){
case 1:
push();
printf("n");
break;
case 2:
pop();
printf("n");
break;
case 3:
if(top>=0){
printf("nt Your Stack n");
for(i=top;i>=0;i--){
printf("nt %dn",A[i]);
}
printf("n");
}
else{
printf("Stack is EMPTY!!");
}
break;
case 4:
printf("%d",(top+1));
printf("n");
break;
case 5:
printf("nt EXITTED...");
break;
default:
printf("nt Not in the above instruction.nn");
}
}
while(k!=5);
return 0;
}

修复您的代码:

for(i=0,m=0;i<=top;i++)
{
if(A[i] != top)
m++;
}

最新更新