2015-11-18 91 views
-1

我在編譯這段代碼時遇到問題,因爲我不知道如何使用typedef(但我們必須)。我的方法推動項目* elem作爲輸入,但頂部 - >信息= * elem不起作用。這裏是我的代碼:在C中使用typedef和指針來實現堆棧

#include <stdio.h> 
#include <stdlib.h> 



struct node 
{ 
int info; 

struct node *ptr; 
}*top,*top1,*temp; 


typedef struct item { 

} item; 

// my methods 
void push(item *elem); 
void *pop(); 
void empty(); 
void create(); 

int count = 0; 

void create() 
{ 
    top = NULL; 
} 


// pushing the elements in the stack 
void push(item *elem) 
{ 
    if (top == NULL) 
    { 
     top =(struct node *)malloc(1*sizeof(struct node)); 
     top->ptr = NULL; 
     top->info = *elem; 
    } 
    else 
    { 
     temp =(struct node *)malloc(1*sizeof(struct node)); 
     temp->ptr = top; 
     temp->info = *elem; // here is the error "not compatible" 
     top = temp; 
    } 
    count++; 
} 
    // I also got this, this is for creating a new elem, but I do not 
    // know how to implement this method 
    item* new_item(int value) { 

} 
+1

你是什麼意思 '用typedef工作'?你不確定它的用法嗎?當你嘗試使用typedefed類型時你有錯誤嗎?還有別的嗎? – SergeyA

+1

'top-> info = * elem;''info'是一個'int',但'* elem'是一個'item'。 –

+0

我的意思是,我從來沒有使用它。我粗略地理解它的意思,但是當我必須使用它實現一個方法時(這種情況下我的推送方法),對我來說有點困難 – Blnpwr

回答

1

首先,類型定義:

struct node 
{ 
    int info; 
    struct node *ptr; 
}; 
typedef struct node item; 

,並創建一個指針:

item *top = NULL; 

push應該簡單地在堆棧的頂部插入元素。

void push(item *elem) 
{ 
    // I assume elem is already created. 
    if (top == NULL) 
    { 
     top = elem; 
    } 
    else 
    { 
     top->ptr = elem; 
     top = elem; 
    } 
    count++; 
} 

new_item應分配內存和初始化

item* new_item(int value) 
{ 
    item *temp = malloc(sizeof(item)); 
    item->info = value; 
    item->ptr = NULL; 
} 

別的地方,創建並添加....

item *someNewItem = new_item(100); 
push(someNewItem); 
// Later on, someNewItem needs to be free()'d 
+0

您好,感謝您的回答。但是您認爲「elem已經。創造」是我的問題,我不知道如何創建這個 – Blnpwr

+0

它得到的'new_item'函數創建 –

+0

我想你的意思'typedef結構節點項;。'近 – trentcl