#include <stdio.h>
#include <stdlib.h>
//链式栈节点设计
struct node
{
int num; //数据域
struct node *next; //指针域
};
//链式栈节点管理
typedef struct stack_list
{
int count; //链式栈的节点管理
struct node *top; //链式栈节点指针
} sl, *psl;
//链式栈初始化
psl stack_list_init()
{
psl mystack = malloc(sizeof(sl));
if (mystack == NULL)
{
printf("申请链式栈失败\n");
return NULL;
}
mystack->count = 0;
mystack->top = NULL;
return mystack;
}
//压栈
int push_stack_list(psl mystack, int num)
{
struct node *newnode = malloc(sizeof(struct node));
if (newnode == NULL) //判断新节点申请
{
printf("newnode error\n");
return -1;
}
//新节点初始化
newnode->num = num;
newnode->next = NULL;
//插入尾部
newnode->next = mystack->top;
//跟新新的节点
mystack->top = newnode;
// 节点长度加一
mystack->count++;
return 0;
}
//弹栈
int pop_stack_list(psl mystack, int *num)
{
//判断是否为空
if (mystack->count == 0)
{
printf("mystack empty\n");
}
//定义一个指针接收
*num = mystack->top->num;
//跟新新的节点
mystack->top = mystack->top->next;
// 节点减一
mystack->count--;
return 0;
}
int main(int argc, char const *argv[])
{
psl mystack = stack_list_init();
//压栈数据
printf("压栈数据:");
for (int i = 1; i <= 10; i++)
{
push_stack_list(mystack, i);
printf("-%d", i);
}
printf("\n");
//弹栈数据
printf("弹栈数据:");
int num;
for (int i = 1; i <= 10; i++)
{
pop_stack_list(mystack, &num);
printf("-%d", num);
}
printf("\n");
return 0;
}
c语言 数据结构 栈 链式栈
最新推荐文章于 2024-07-18 17:57:16 发布