链式栈实现
#include <stdio.h>
#include <stdlib.h>
/*
入栈: 表头法插入
出栈: 表头法删除
*/
typedef struct Node_tlg {
int data;
struct Node_tlg* next;
}NODE,*LPNODE;
typedef struct {
LPNODE stackTop;
int size;
}STACK,*LPSTACK;
//节点创建
LPNODE createNode(int data) {
LPNODE newNode = (LPNODE)malloc(sizeof(NODE));
if (NULL == newNode) {
printf("节点内存申请失败!\n");
return NULL;
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
//栈创建
LPSTACK createStack() {
LPSTACK stack = (LPSTACK)malloc(sizeof(STACK));
if (NULL == stack) {
printf("栈内存申请失败!\n");
return NULL;
}
stack->stackTop = NULL;
stack->size = 0;
return stack;
}
//入栈(头插法)
void push(LPSTACK stack,int data) {
LPNODE newNode = createNode(data);
newNode->next = stack->stackTop;
stack->stackTop = newNode;
stack->size++;
}
//出栈(头删法)
void pop(LPSTACK stack) {
if (stack->stackTop == NULL) {
printf("栈空\n");
return;
}
/*LPNODE delNode = stack->stackTop;
stack->stackTop = delNode->next;
free(delNode);
delNode = NULL;*/
LPNODE nextNode = stack->stackTop->next;
free(stack->stackTop);
stack->stackTop = nextNode;
stack->size--;
}
//返回栈顶元素
int top(LPSTACK stack) {
if (empty(stack))
return -1;
return stack->stackTop->data;
}
//万金油函数
int empty(LPSTACK stack) {
return stack->size == 0;
}
int stackSize(LPSTACK stack) {
return stack->size;
}
//栈销毁
void destroyStack(LPSTACK* stack) {
if (NULL != *stack) {
while (!empty(*stack)) {
pop(*stack);
}
free((*stack)->stackTop);
(*stack)->stackTop = NULL;
free(*stack);
*stack = NULL;
}
}
int main()
{
LPSTACK stack = createStack();
for (int i = 0; i < 5; i++)
{
push(stack, i);
}
while (!empty(stack)) {
printf("%d\t", top(stack));
pop(stack);
}
printf("\n");
destroyStack(&stack);
if (stack == NULL) {
printf("栈销毁成功!\n");
}
system("pause");
return 0;
}