2017-11-25 109 views
-1

我目前正試圖做一個簡單的堆棧菜單程序,將推動和彈出用戶輸入的值。 (也打印出堆棧)。堆棧將不會存儲在C的價值

這是我迄今爲止的代碼。當我嘗試插入一個值(情況1)時,我認爲它有效 - 但我不確定,因爲當我嘗試打印出堆棧時(情況3),它總是說「堆棧爲空!」。當我嘗試彈出堆棧時(情況2),它只是崩潰。

我不知道我的一個結構是否關閉,或者我的指針是不正確的。

感謝您提前給予您的幫助,我非常抱歉亂碼 - 我對此仍然很陌生!

#include<stdio.h> 
#include<stdlib.h> 
#define EMPTY 0 

struct node 
{ 
    int data; 
    struct node *link; 
}; 
typedef struct node Stack; 

Stack* get_node() 
{ 
    Stack *tmp; 
    tmp = (Stack*) malloc(sizeof(Stack)); 
    tmp->link = EMPTY; 
    return tmp; 
} 

void push(Stack **top, int data) 
{ 
    Stack *tmp; 
    tmp = *top; 

    *top = get_node(); 

    (*top)->data = data; 
    (*top)->link = tmp; 
} 

void pop(Stack **top) 
{ 
    Stack *tmp; 
    int num; 
    if (top == EMPTY) 
    { 
     printf("Stack is Empty!"); 
    } 
    else 
    { 
     tmp = *top; 
     printf("%d", tmp->data); 
     *top = tmp->link; 
     free(tmp); 
    } 
} 

void stack(Stack *top) 
{ 
    if (top == EMPTY) 
    { 
     printf("Stack is Empty..."); 
    } 
    else 
    { 
     Stack *tmp = top; 
     while (tmp->link != EMPTY) 
     { 
      printf("%d", tmp->data); 
      tmp = tmp->link; 
     } 
    } 
} 

void menu(int choice) 
{ 
    Stack *top = EMPTY; 
    int data; 

    switch (choice) 
    { 
     case 1: 
      printf("Enter Data : "); 
      scanf_s("%d", &data); 
      push(&top, data); 
      break; 

     case 2: 
      pop(&top); 
      break; 

     case 3: 
      stack(top); 
      break; 

     case 4: 
      exit(1); 
    } 
} 

void main() 
{ 
    int choice; 

    printf("< < = M e n u = = >\n"); 
    printf("1.push\n"); 
    printf("2.pop\n"); 
    printf("3.print_all\n"); 
    printf("4.quit\n"); 
    printf("Select : "); 
    while (1) 
    { 
     scanf_s("%d", &choice); 
     menu(choice); 
    } 
} 
+2

「我的代碼有什麼問題」:這是一個非常糟糕的方式來描述你的問題。 –

+0

哦,我很抱歉,這是我第一次使用這個網站,我不知道如何製作一個好標題。我應該怎樣編輯它? – Kitty

+2

你應該把問題縮小到[mcve]。然後你就會知道要改變的標題 –

回答

0

做一些小改動喜歡做toppointerstaticmenu()功能,因爲如果你不讓它爲static,它得到每一個與zero初始化時間。 替換此

Stack *top = EMPTY; 

static Stack *top ; 

和修改stack()功能,打印一張少元素

void stack(Stack *top) 
{ 
    if (top == EMPTY) 
    { 
     printf("Stack is Empty..."); 
    } 
    else 
    { 
     Stack *tmp = top; 
     while (tmp != EMPTY) // here you wrote as tmp->link 
     { 
      printf("%d \n ", tmp->data); 
      tmp = tmp->link; 
     } 
    } 
} 

其餘所有的邏輯是正確的。我希望它有幫助。

0

你實際上並沒有把棧放在任何地方。每次在菜單中輸入選項時,menu函數都會以空的Stack開頭。當您插入,然後打印出Stack時,它將每次都有一個空的Stack

void menu(int choice) 
{ 
    Stack *top = EMPTY; // Problem - Always empty Stack for each call 
    int data; 
    ... 
} 

要解決這個問題,你需要要麼有一個全局變量Stack或通過Stack爲每一個使用功能。