链式栈
代码实现
//定义头文件
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
//int 重命名
typedef int dataType;
//定义链表结构体
typedef struct node
{
dataType data;
struct node* next;
}node;
//定义栈结构体
typedef struct stack
{
dataType size;
struct node* top;
}stack;
//初始化栈链表
stack* init_linkstack(dataType size)
{
stack* ls = malloc(sizeof(stack));
if(ls == NULL)
return NULL;
ls->size = 0;
ls->top = NULL;
return ls;
}
//判空
bool is_empty(stack* ls)
{
return ls->top == NULL;
}
//创建新节点
node* creat_node(stack* ls,dataType data)
{
node* pnew = malloc(sizeof(node));
if(pnew == NULL)
return pnew;
pnew->data = data;
pnew->next = NULL;
return pnew;
}
//入栈
bool push(stack* ls, dataType data)
{
node* pnew = creat_node(ls,data);
pnew->next = ls->top;
ls->top = pnew;
ls->size++;
return true;
}
//出栈
bool pop(stack* ls)
{
if(is_empty(ls))
return false;
node* p = ls->top;
ls->top = p->next;
p->next = NULL;
free(p);
ls->size--;
return true;
}
//读取栈顶元素
dataType getdata(stack* ls)
{
if(is_empty(ls))
return -1;
node* p = ls->top;
printf("栈顶元素为:%d\n",p->data);
}
int main(int argc, char const *argv[])
{
stack * ls = init_linkstack(10);
push(ls,1);
push(ls,2);
push(ls,3);
pop(ls);
getdata(ls);
return 0;
}