2

所以,我自己编写了一个程序来将用户输入插入堆栈。但是,尽管我进行了严格的尝试,我还是无法正确插入数据。它显示数据已插入,但显示时显示垃圾值。这是我的主要功能:

//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;
   }

这是我的推送功能:

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;
}

这是我的表演功能:

void show_stack(int newstack[], int bound)
{
int i;
printf("\n");
for(i=0;i<=bound;i++)
printf("%d",newstack[i]);
 }     

请帮我找出错误。

4

2 回答 2

5

您正在传递数组长度并打印所有数组元素。所以你看到垃圾价值。尝试仅打印插入的元素。

 show_stack(stack, top);

你的函数原型应该是

void show_stack(int *,int);

无论溢出如何,您每次都会增加您的 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
    }
}
于 2013-09-12T06:33:12.790 回答
4

show_stack使用容量 ( MAXSTK) 调用,而不是其实际大小。因此,它将显示 中的所有元素stack,无论它们具有什么值。简单地调用它top应该可以解决问题。

另一个注意事项:您的声明show_stack与实现的参数列表不匹配。

于 2013-09-12T06:31:26.100 回答