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我的坏,编辑 –