2014-03-03 42 views
1

我正在嘗試將用戶輸入的項目推入C中的堆棧(鏈接列表結構),但我希望能夠以各種不同類型輸入到堆棧中。現在我的籌碼只能採取INT,但我希望它能夠採取在其他類型,如字符,雙,浮法,等C中的標籤類型

我的代碼迄今:

#include <stdio.h> 
#include <conio.h> 
#include <string.h> 
#include <stdlib.h> 
#include <stdbool.h> 
#include <ctype.h> 


typedef struct stack 
{ 
    int val; 
    struct stack *next; 
}node; 

node *head = NULL; 

void Push (int Item, node **head) 
{ 
    node *New; 
    node *get_node(int); 
    New = get_node(Item); 
    New->next = *head; 
    *head = New; 
} 

node *get_node(int item) 
{ 
    node *temp; 
    temp = (node*)malloc(sizeof(node)); 
    if (temp == NULL) printf("Memory Cannot Be Allocated"); 
    temp->val = item; 
    temp->next = NULL; 
    return (temp); 
} 

int Sempty (node *temp) 
{ 
    if(temp == NULL) 
     return 1; 
    else 
     return 0; 
} 

int Pop (node **head) 
{ 
    int item; 
    node *temp; 
    item = (*head)->val; 
    temp = *head; 
    *head = (*head)->next; 
    free(temp); 
    return(item); 
} 

void Display (node **head) 
{ 
    node *temp; 
    temp = *head; 
    if(Sempty(temp)) printf("The stack is empty\n"); 
    else 
    { 
     while (temp != NULL) 
     { 
      printf("%s", temp->val); 
      temp = temp->next; 
     } 
    } 
} 

void main() 
{ 
    char* in; 
    int data, item, i; 
    char length[5]; 
    for(i = 0; i <= sizeof(length); i++) 
    { 
    printf("Enter a value: "); 
    scanf("%c", &in); 
    strcpy(in, in); 
    Push(in, &head); 
    Display(&head); 
    } 

} 
+1

只是使用指針作爲「item」類型。那麼你可以存儲幾乎任何東西的指針。一個指針就是一個指針......它將使用你的堆棧來判斷這些指針是什麼。 –

回答

3

我會使用一個無效指針並在需要時進行強制轉換。你不能直接存儲它的類型,但你仍然可以使用一個int變量來訪問一個函數指針數組中正確的函數,這個函數指針將使用正確的cast。

typedef struct stack 
{ 
    void *val; 
    int type; 
    struct stack *next; 
}node; 

隨着類型符合函數指針陣列中的一個功能。 How can I use an array of function pointers?

您還可以在您的「類型」(絕對佔用)上製作一個簡單的開關盒。

編輯: 簡單的例子:

while (root != NULL) 
    { 
     switch (root->type) { 
     case 0: 
      printf("%d\n", *(int *)(root->val)); 
      break; 
     case 1: 
      printf("%c\n", *(char *)(root->val)); 
      break; 
     default: 
      printf("unexpected type\n"); 
     } 
     root = root->next; 
    } 

這很可能會令更多SENS用炭,而不是一個int,所以你可以只執行情況「C」的情況下「I」。

要小心,你有一個void *,它是一個指向你的變量的指針,不要忘記分配它。

root->val = malloc(sizeof(int)); 
*(int *)(root->val) = 2; 
+0

好吧,所以每當我想將值推入堆棧時,我必須使用switch語句的if語句來指定類型?你能舉一個例子嗎?@Phibonacci –

+0

我編輯了我的文章。 'root'是鏈接列表的第一個元素。 – Jean

+0

說實話,我現在很困惑,現在哈哈。我想將用戶值推入堆棧,但能夠區分它們是什麼類型,因此當我調用像「add」這樣的函數時,能夠檢查前兩個值是否是整數。 –

1
typedef struct stack 
{ 
    int type; 
    void *ptr; 
    struct stack *next; 
}node; 

根據你想存儲什麼類型的元素,你可以做一個適當的malloc指向ptr。

+0

好吧,所以只要我想將值推入堆棧,我必須使用switch語句的if語句來指定類型?你能舉一個例子嗎?@ user376507 –

+0

對不起,延遲響應,看起來像某人已經發布了一個例子。希望有所幫助。 – user376507

+0

是的,無論如何。快速的問題。我試圖彈出堆棧的第一個元素,但我不知道如何做到這一點,當我有2種不同的數據類型(char *&double)。你有好主意嗎? @ user376507 –