Mis*_*u4u 2 c stack data-structures
所以,我编写了一个程序来自己将一个用户输入插入到堆栈中.但是,尽管我进行了严格的尝试,但我无法正确插入数据.它显示已插入数据,但在显示时,显示垃圾值.这是我的主要功能:
//Stack
#include<stdio.h>
#include<stdlib.h>
#define MAXSTK 10
void push(int *, int, int *, int);
//void pop();
void show_stack();
int main()
{
int ch, ch1, stack[MAXSTK], top=-1;
do{
printf("\n <<Stack MENU>>");
printf("1. Add Element");
printf("2. Delete Element");
printf("3. Show Stack");
printf("4. Exit menu");
printf("\n Enter your choice->");
scanf("%d", &ch);
switch(ch)
{
case 1: printf("\n Enter element to add->");
scanf("%d",&ch1);
push(stack,ch1, &top, MAXSTK);
break;
/* case 2: pop();
break;*/
case 3: printf("\n The stack is->");
show_stack(stack, MAXSTK);
break;
default: printf("\n Invalid Choice!!!");
break;
}
}while(ch!=4);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是我的推送功能:
void push(int newstack[], int num, int *newtop, int bound)
{
*newtop=*newtop+1;
if(*newtop==0)
printf("\n Stack was Empty. New Value inserted.");
if(*newtop>(bound-1))
{
printf("\n Caution! OVERFLOW!!!");
}
newstack[*newtop]=num;
}
Run Code Online (Sandbox Code Playgroud)
这是我的show功能:
void show_stack(int newstack[], int bound)
{
int i;
printf("\n");
for(i=0;i<=bound;i++)
printf("%d",newstack[i]);
}
Run Code Online (Sandbox Code Playgroud)
请帮我找错.
您正在传递数组长度并打印所有数组元素.所以你看到垃圾价值.尝试仅打印插入的元素.
show_stack(stack, top);
Run Code Online (Sandbox Code Playgroud)
你的函数原型应该是
void show_stack(int *,int);
Run Code Online (Sandbox Code Playgroud)
无论溢出,你每次都会增加你的newtop.这是一个不好的做法.popping()和show_stack()会导致问题.你可以做这样的事情来避免它.
void push(int newstack[], int num, int *newtop, int bound)
{
// if newtop is < 0 display the message
if(*newtop<0)
printf("\n Stack was Empty. New Value inserted.");
// newtop will always point to top element. so if newtop is 9 it means your stack is full. so if newtop is >= bound-1(9) stack is full
if(*newtop>=(bound-1))
printf("\n Caution! OVERFLOW!!!");
else
{
*newtop=*newtop+1; //increment newtop
newstack[*newtop]=num; //store value in newtop
}
}
Run Code Online (Sandbox Code Playgroud)