#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#define TYPE int
typedef struct Node
{
TYPE data;
struct Node* next;
}Node;
Node* creat_node(TYPE data)
{
Node* node = malloc(sizeof(Node));
node->data=data;
node->next = NULL;
return node;
}
typedef struct Stack
{
Node* top;
size_t len;
}Stack;
//创建
Stack* creat_stack(void);
//销毁
void destory_stack(Stack* stack);
//栈空
bool empty_stack(Stack* stack);
//入栈
void push_stack(Stack* stack,TYPE data);
//出栈
bool pop_stack(Stack* stack);
//栈顶
TYPE* top_stack(Stack* stack);
//----------------以上为函数声明----------------
int main()//main函数用于测试
{
Stack* stack = creat_stack();
for(int i=0;i<10;i++)
{
push_stack(stack,i);
printf("top:%d\n",*top_stack(stack));
}
printf("------------\n");
for(int i=0;i<10;i++)
{
printf("top:%d ",*top_stack(stack));
printf("%s \n",pop_stack(stack)?"ok":"no");
}
}
//------------------以下为实现函数------------------
//创建
Stack* creat_stack(void)
{
Stack* stack = malloc(sizeof(Stack));
stack ->top =NULL;
stack ->len = 0;
return stack;
}
//销毁
void destory_stack(Stack* stack)
{
while(pop_stack(stack));
free(stack);
}
//栈空
bool empty_stack(Stack* stack)
{
return NULL == stack->top;
}
//入栈
void push_stack(Stack* stack,TYPE data)
{
Node* node = creat_node(data);
node->next = stack->top;
stack->top = node;
stack->len++;
}
//出栈
bool pop_stack(Stack* stack)
{
if(empty_stack(stack)) return false;
Node* node = stack->top;
stack->top = node->next;
free(node);
stack->len--;
}
//栈顶
TYPE* top_stack(Stack* stack)
{
if(empty_stack(stack))return NULL;
return &stack->top->data;
}
C语言 建立简单的链表栈
最新推荐文章于 2022-05-21 23:12:32 发布