2015-06-20 35 views
0

我試圖實現一個堆棧。我想出了這個。所有其他函數按預期工作,除非試圖推送。當我嘗試推動4發生一些奇怪的事情。做奇怪的行爲,而

#include <stdio.h> 
#include <stdlib.h> 
#define MAX 10 

typedef struct 
{ 
    int a[MAX]; 
    int top; 
}stack; 

void init(stack *p) 
{ 
    p->top=-1; 
} 

int full(stack *p) 
{ 
    if(p->top==MAX) 
     return 1; 
    else 
     return 0; 
} 

int empty(stack *p) 
{ 
    if(p->top==-1) 
    { 
     init(p); 
     return 1; 
    } 
    else 
     return 0; 
} 

void display(stack *p) 
{ 
    if(!empty(p)) 
    { 
     printf("Stack is::\n"); 
     for(int i=0;i<=p->top;++i) 
      printf("%d\t",p->a[i]); 
     printf("\n"); 
    } 
    else 
    { 
     printf("Stack is empty.\n"); 
     init(p); 
    } 
} 

void push(stack *p, int x) 
{ 
    if(!full(p)) /*full() returns 1 is top==max, 0 otherwise*/ 
    { 
     p->a[p->top++]=x; 
     printf("%d pushed.\n",x); 
    } 
    else 
     printf("Stack is full.\n"); 
} 

void pop(stack *p) 
{ 
    if(!empty(p)) 
     printf("%d popped.\n",p->a[p->top--]); 
    else 
    { 
     printf("Stack is empty.\n"); 
     init(p); 
    } 
} 

int main() 
{ 
    stack p; 
    int ch,x; 
    printf("Hello world!\n"); 
    init(&p); 
    printf("*****MENU*****\n"); 
    do{ 
     printf("1.Push\n2.Pop\n3.Display\n4.Exit\n"); 
     printf("Enter your choice:: "); 
     scanf("%d",&ch); 
     switch(ch) 
     { 
      case 1: 
       printf("Enter element to push:: "); 
       scanf("%d",&x); 
       push(&p,x); 
       break; 
      case 2: 
       pop(&p); 
       break; 
      case 3: 
       display(&p); 
       break; 
      case 4: 
       exit(1); 
     } 
    }while(ch!=4); 
    return 0; 
} 

該程序終止。

我用ch(= 1)而不是x(= 4)測試while循環。那麼爲什麼會發生?

+1

請不要張貼截圖,但文字。你的電腦增長了多久,跑了嗎? - 這個我會稱之爲「奇怪的行爲」。 – Olaf

+0

據估計,代碼未被呈現的部分存在問題。 – BLUEPIXY

+0

發表了完整的代碼。 –

回答

0

此功能

void push(stack *p, int x) 
{ 
    if(!full(p)) /*full() returns 1 is top==max, 0 otherwise*/ 
    { 
     p->a[p->top++]=x; 
     printf("%d pushed.\n",x); 
    } 
    else 
     printf("Stack is full.\n"); 
} 

是錯誤的。頂部的初始值是-1所以在此聲明

p->a[p->top++]=x; 

你正試圖將值存儲在與該指數等於-1數組的元素。

因此該程序具有未定義的行爲。

功能可能看起來像

void push(stack *p, int x) 
{ 
    if (!full(p)) /*full() returns 1 if top + 1 == max, 0 otherwise*/ 
    { 
     p->a[++p->top]=x; 
      ^^^^^^^^ 
     printf("%d pushed.\n",x); 
    } 
    else 
    { 
     printf("Stack is full.\n"); 
    } 
} 

考慮到,在這種情況下,功能完全應該像

int full(const stack *p) 
{ 
    return p->top + 1 == MAX; 
      ^^^^^^^^^^ 
} 

功能空也可以寫成簡單的

int empty(const stack *p) 
{ 
    return p->top == -1; 
} 

而且堆棧通常按照與輸入元素順序相反的順序打印

void display(const stack *p) 
{ 
    if (!empty(p)) 
    { 
     printf("Stack is::\n"); 
     for (int i = p->top; i != -1; --i) 
      printf("%d\t", p->a[i]); 
     printf("\n"); 
    } 
    else 
    { 
     printf("Stack is empty.\n"); 
    } 
}