【发布时间】:2016-06-30 17:15:13
【问题描述】:
这是使用链表实现堆栈的完整代码。它来自 James Aspnes 为耶鲁大学撰写的数据结构笔记(有什么好处吗?)
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
struct elt {
struct elt *next;
int value;
};
/*
* We could make a struct for this,
* but it would have only one component,
* so this is quicker.
*/
typedef struct elt *Stack;
#define STACK_EMPTY (0)
/* push a new value onto top of stack */
void
stackPush(Stack *s, int value)
{
struct elt *e;
e = malloc(sizeof(struct elt));
assert(e);
e->value = value;
e->next = *s;
*s = e;
}
int
stackEmpty(const Stack *s)
{
return (*s == 0);
}
int
stackPop(Stack *s)
{
int ret;
struct elt *e;
assert(!stackEmpty(s));
ret = (*s)->value;
/* patch out first element */
e = *s;
*s = e->next;
free(e);
return ret;
}
/* print contents of stack on a single line */
void
stackPrint(const Stack *s)
{
struct elt *e;
for(e = *s; e != 0; e = e->next) {
printf("%d ", e->value);
}
putchar('\n');
}
int
main(int argc, char **argv)
{
int i;
Stack s;
s = STACK_EMPTY;
for(i = 0; i < 5; i++) {
printf("push %d\n", i);
stackPush(&s, i);
stackPrint(&s);
}
while(!stackEmpty(&s)) {
printf("pop gets %d\n", stackPop(&s));
stackPrint(&s);
}
return 0;
}
我能理解大部分代码。但我无法理解这部分
typedef struct elt *Stack;
为什么在 Stack 前面有一个 * 是什么意思?
我正在寻找指针的概念,尤其是在难以掌握的函数返回类型方面。 提前致谢。
【问题讨论】:
-
这不是一个辅导网站。指针的概念非常广泛,应该使用专门的资源进行研究。
-
这是
C代码,而不是 C++。这一行:e = malloc(sizeof(struct elt));不会编译为 C++。 -
@PaulMcKenzie:代码中的什么阻止了代码被编译为 C++?
-
@ThomasMatthews
malloc的返回值没有被强制转换。 C++ 需要强制转换。 -
@PaulMcKenzie 我知道它是 C。我标记了两者,因为两者相似。我的错。
标签: c++ c pointers data-structures stack