预处理
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#define MAX 10
封装节点
struct Node {
int data;
struct Node* next;
};
封装链表
struct Stack {
struct Node* headNode;
int curSize;
};
创建节点和链表
Stack* CreateStack() {
Stack* stack = (Stack*)calloc(1, sizeof(Stack));
assert(stack);
stack->headNode = NULL;
stack->curSize = 0;
return stack;
}
Node* CreateNode(int Mydata) {
Node* newNode = (Node*)malloc(sizeof(Node));
assert(newNode);
newNode->data = Mydata;
newNode->next = NULL;
return newNode;
}
入栈
void Push(Stack* stack,int Mydata) {
if (stack->curSize == MAX)
return;
Node* newNode = CreateNode(Mydata);
newNode->next = stack->headNode;
stack->headNode = newNode;
stack->curSize++;
}
出栈
void Pop(Stack* stack) {
if (stack->curSize == 0)
return;
Node* nextNode = stack->headNode->next;
free(stack->headNode);
stack->headNode = nextNode;
stack->curSize--;
}
获取栈顶元素
int top(Stack* stack) {
return stack->headNode->data;
}
判空
bool temp(Stack* stack) {
return stack->curSize == 0;
}
测试代码:
int main() {
Stack* stack = CreateStack();
printf("入栈:\t");
for (int i = 0; i < 10; i++) {
printf("%d\t", i);
Push(stack, i);
}
printf("\n出栈:\t");
while (!temp(stack)) {
printf("%d\t", top(stack));
Pop(stack);
}
return 0;
}
效果如下: