PNT是一個指針,如宣佈,
struct stack *pnt;
struct stack *prev;
它指向擊中宣佈棧由
struct stack
{
int value;
struct stos *w; // struct stos should struct stack
};
你缺少來自其他代碼本聲明。
typedef struct stos{
int value;
struct stos *next;
} stos;
所以,這是提升有問題,很多問題代碼...
讓我們開始
首先解決STOS爛攤子:
問題的兩個結構上面被解除(複製/粘貼),所以而不是struct stack
包含一個指向相同類型結構的指針正在尋找一個未定義的結構struct stos *next;
它應該是struct stack* next;
typedef struct Stack;
typedef struct stack {
int value;
Stack* next;
} Stack;
struct stack *pnt; // pnt = pointer top of stack
struct stack *prev; // prev = pointer to the previous stack item
所以現在我們知道棧被保存爲棧結構的單獨鏈接列表。
讓我們破譯void push(int x)
void push(int x)
{
// point prev to pnt, previous to top of stack
prev = pnt;
// create a new item to place on the top of the stack
pnt = (struct stack*)malloc(sizeof(struct stack));
// initial the value member of the new item with x
pnt->value=x;
// point the new item's link point to point the previous top of the stack
pnt->w = prev;
// print the value contained in the new top of the stack item.
printf("Top of stack: %d\n", pnt->value);
}
這個函數是一個災難,因爲它使用關鍵字new
作爲變量的名稱。是的,new
在C++中。但爲什麼要爲下一個人制造一團糟。
void delete(struct stos *new)
{
if (new!=NULL)
{
prev = new->w;
printf("Deleted: %d\n", new->value);
free(new);
pnt = prev;
}
else printf("Stack is empty\n");
}
應該已被寫入如下...
// forward declaration of Stos because it won't be defined until the end of struct it is used in.
typedef struct {
int value;
struct Stack* next;
} Stack;
Stack* pnt; // pnt = pointer top of stack
Stack* prev; // prev = pointer to the previous stack item
使用Stack* pnt
與Stack *pnt
說,與「指針稱爲PNT指向棧」「叫PNT堆棧指針」。 (還有一個螺旋訣竅可以更容易地閱讀這些聲明Q.E.D)
void delete(Stack* pNew)
{
if (pNew)
{
prev = pNew->w;
printf("Deleted: %d\n", pNew->value);
free(pNew);
pnt = prev;
}
else printf("Stack is empty\n");
}
正如我所說的,這是一團糟。 什麼是重要的是你問了一個問題,並希望已經學會了一些東西,這將幫助你在你的下一段代碼。
一旦你創建了一個typedef,然後使用它。降struct stack
東西
使變量的名字足夠長的時間,使未來的讀者會理解的代碼Stack* pTopOfStack;
儘量不要使用那些衍生的關鍵字詞new
不要過度人羣冗餘代碼
if (new != NULL)
與if (new)
代碼,甚至更好if (pNewStackItem)
更好地完全理解代碼的作用,而不是讓更復雜的東西看起來正確,編譯和運行。永遠不要相信程序員,「對不起,它適用於我的機器。」
使用Google會更好.. – Aditya
'struct stos' ?? –
@Weather Vane我的壞,編輯 –