基本结构
typedef struct Linknode {
ElemenType data; //数据域
struct Linknode *next; //指针域
} * LiStack; //栈类型定义
实现代码
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int value;
struct Node *next;
}Node;
typedef struct {
Node *top;
int count;
} Stack;
bool init(Stack *s);
bool push(Stack *s, int e);
bool pop(Stack *s, int *e);
int main() {
int i, e;
Stack s;
init(&s);
for (i = 0; i < 5; i++) {
push(&s, i);
pop(&s, &e);
printf("%d\n", e);
}
return 0;
}
bool init(Stack *s) {
s->top = NULL;//初始化为空栈
s->count = 0;
return true;
}
bool push(Stack *s, int e) {
Node *newNode = (Node*)malloc(sizeof(Node));
if (NULL == newNode)
{
return false;
}
newNode->next = s->top;
newNode->value = e;
s->top = newNode;
s->count ++;
return true;
}
bool pop(Stack *s, int *e) {
Node *temp = NULL;
if (0 == s->count) {
return false;
}
temp = s->top;
*e = temp->value;
s->top = temp->next;
free(temp);
s->count --;
return true;
}