【发布时间】:2020-09-15 21:14:15
【问题描述】:
我尝试编写一个程序来实现堆栈中的各种操作,如弹出、推送、遍历、窥视等。但我使用了静态内存分配。如何使用动态内存分配实现程序?
(我是编程初学者,对动态内存分配没有深入了解)。
这是我使用静态内存分配的程序:
#include<stdio.h>
#define CAPACITY 5
int stack[CAPACITY] ,top=-1;
void main()
{
int ch,item;
while(1)
{
printf("1.push\n");
printf("2.pop\n");
printf("3.peek \n");
printf("4.traverse\n");
printf("5.Quit\n");
printf("Enter your choice :\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Enter the element to push :\n");
scanf("%d",&item);
push(item);
break;
case 2:
item = pop();
if(item==0)
{
printf("stack is underflow\n");
}
else
{
printf("popped item : %d\n",item);
}
break;
case 3: peek();
break;
case 4: traverse();
break;
case 5: exit(0);
default:printf("Invalid input \n\n");
}
}
}
void push(int ele)
{
if(isfull())
{
printf("Stack is overflow\n");
}
else
{
top++;
stack[top] = ele;
printf("%d pushed \n",ele);
}
}
int isfull()
{
if(top==CAPACITY-1)
{
return 1;
}
else
{
return 0;
}
}
int pop()
{
if(isempty())
{
return 0;
}
else
{
return stack[top--];
}
}
int isempty()
{
if(top==-1)
{
return 1;
}
else
{
return 0;
}
}
void peek()
{
if(isempty())
{
printf("stack is underflow\n");
}
else
{
printf("peek element :%d\n",stack[top]);
}
}
void traverse()
{
if(isempty())
{
printf("stack is empty\n");
}
else
{
int i;
printf("Stack elements are : \n");
for(i=0;i<=top;i++)
{
printf("%d \n",stack[i]);
}
}
}
【问题讨论】:
-
OT:是什么导致了 push 1、push 2、push 0、pop?你认为下溢消息正确吗?
-
@SergeBallesta 我真的不知道。我试过这样做,它运行良好。
-
@MichaelBianconi 我正在检查。
-
我没有说有错误。我只是说那个用例中的消息
stack is underflow是无关紧要的。
标签: c memory dynamic stack allocation