【问题标题】:Correct value of the user input is not getting inserted into the stack用户输入的正确值未插入堆栈
【发布时间】:2013-09-12 06:24:32
【问题描述】:

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

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

请帮我找出错误。

【问题讨论】:

    标签: c data-structures stack


    【解决方案1】:

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

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

    【讨论】:

    • 精彩的解释。感谢您还指出推送功能中的逻辑错误。你提到的错误也弄乱了我的堆栈;我是在表演的时候抓到的。 +1
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2012-11-09
      • 1970-01-01
      • 1970-01-01
      • 2013-01-18
      • 2021-10-01
      • 1970-01-01
      • 2013-06-28
      • 2021-01-11
      • 1970-01-01
      相关资源
      最近更新 更多