防止数组接受重复值

时间:2016-03-15 17:21:18

标签: c

我有一个堆栈,我想推送不同的元素。我写了以下代码。但它总是只检查第一个元素。如果我输入重复值第一个值,它不会接受,但如果我输入第二个或第三个值的重复值,它会接受它。 例如,如果我输入20并再次输入20,则不接受第二个, 但如果我输入20,22,22则接受重复。我该如何防止这种情况?

#include <stdio.h>
#define MAXSIZE 5

struct stack
{
    int stk[MAXSIZE];
    int top;
};
typedef struct stack STACK;
STACK s;

void push(void);
int  pop(void);
void display(void);

void main ()
{
    int choice;
    int option = 1;
    s.top = -1;

    printf ("STACK OPERATION\n");
    while (option)
    {
        printf ("------------------------------------------\n");
        printf ("      1    -->    Bus Status               \n");
        printf ("      2    -->    Enter Bus              \n");
        printf ("      3    -->    Exit Bus               \n");
        printf ("      4    -->    EXIT           \n");
        printf ("------------------------------------------\n");

        printf ("Enter your choice\n");
        scanf    ("%d", &choice);
        switch (choice)
        {
        case 1:
            display();
            break;
        case 2:
            push();
            break;
        case 3:
            pop();
            break;
        case 4:
            return;
        }
        fflush (stdin);
        printf ("Do you want to continue(Type 0 or 1)?\n");
        scanf    ("%d", &option);
    }
}

/*  Function to add an element to the stack */
void push ()
{
    int num,i,j,status=0;
    if (s.top == (MAXSIZE - 1))
    {
        printf ("Terminal is Full\n");
        return;
    }
    else
    {

        printf ("Enter the Bus Number\n");
        scanf ("%d", &num);
        if(num<1 || num>30) {
            printf("This bus Does not Exist.\n");
        }
            for(i=0;i<5;i++){
                if(s.stk[i]==num){
                    printf("Bus Already in the Terminal\n");
                    break;
                }
                else {
                    s.top = s.top + 1;
                    s.stk[s.top] = num;
                    status=1;
                    break;
                }
            }
        if(status==1)
            printf("Bus %d Successfully Entered\n", num);

    }
    return;
}

1 个答案:

答案 0 :(得分:2)

您的总线插入循环正在循环并在第一次找到 s.stk [i]!= num 时添加总线。您需要检查总线是否在站中,即在插入新总线之前搜索整个堆栈。

for(i=0;i<5;i++) {
  if(s.stk[i]==num){
    printf("Bus Already in the Terminal\n");
    break;
  }
  else {
    s.top = s.top + 1;
    s.stk[s.top] = num;
    status=1;
    break;
  }
}