C语言链式栈
stack.h
typedef struct Node_s {
int data;
struct Node_s *pNext;
} Node_t, *pNode_t;
typedef struct Stack_s {
pNode_t pHead;//栈顶指针,指向了链表的第一个结点
int size;//栈的元素个数
} Stack_t, *pStack_t;
void init(pStack_t pStack);
void push(pStack_t pStack, int data);
int isEmpty(pStack_t pStack);
void pop(pStack_t pStack);
int top(pStack_t pStack);
int size(pStack_t pStack);
main.c
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "stack.h"
int main() {
Stack_t stack;
init(&stack);
for (int i = 0; i < 5; ++i) {
push(&stack, i);
printf("top = %d\n", top(&stack));
}
for (int i = 0; i < 6; ++i) {
pop(&stack);
printf("pop, top = %d\n", top(&stack));
}
}
//初始化
void init(pStack_t pStack) {
memset(pStack, 0, sizeof(Stack_t));
}
//压栈
void push(pStack_t pStack, int data) {
pNode_t pNew = (pNode_t)calloc(1, sizeof(Node_t));
pNew->data = data;
//这个链表只有pHead没有pTail,所以不用判断是否为空
pNew->pNext = pStack->pHead;
pStack->pHead = pNew;
++pStack->size;
}
//判空
int isEmpty(pStack_t pStack) {
return pStack->size == 0;
}
//弹栈
void pop(pStack_t pStack) {
if (isEmpty(pStack)) {
fprintf(stderr, "Stack is empty!\n");
return -1;
}
pNode_t pCur = pStack->pHead;
pStack->pHead = pCur->pNext;
free(pCur);
pCur = NULL;
--pStack->size;
}
//获取栈顶数据
int top(pStack_t pStack) {
if (isEmpty(pStack)) {
fprintf(stderr, "Stack is empty!\n");
return -1;
}
return pStack->pHead->data;
}
//获取栈的大小
int size(pStack_t pStack) {
return pStack->size;
}