链式栈操作函数原型声明
node_t *init();
int empty(node_t *top);
datatype read(node_t *top);
void display(node_t *top);
node_t *push(node_t *top,datatype x);
node_t *pop(node_t *top);
链式栈数据结构定义
typedef int datatype;
typedef struct node
{
datatype info;
struct node * next;
}node_t;
完整代码
#include <stdio.h>
#include <malloc.h>
typedef int datatype;
typedef struct node
{
datatype info;
struct node * next;
}node_t;
node_t *init();
int empty(node_t *top);
datatype read(node_t *top);
void display(node_t *top);
node_t *push(node_t *top,datatype x);
node_t *pop(node_t *top);
node_t *init()
{
/*
node_t *top = (node_t *)malloc(sizeof(node_t));
if(!top)
{
printf("maloc err!");
return NULL;
}
else
{
top->next = NULL;
}
*/
return NULL;
}
int empty(node_t *top)
{
if(!top)
{
return 0;
}
return 1;
}
datatype read(node_t *top)
{
if(!top)
{
printf("no data no node error !\n");
return -1;
}
return top->info;
}
void display(node_t *top)
{
node_t *p = top;
printf("----- show stack data -----\n");
while(p)
{
printf("%d\n",p->info);
p = p->next;
}
}
node_t *push(node_t *top,datatype x)
{
node_t *p = top;
if(!top)
{
p = (node_t *)malloc(sizeof(node_t));
if(!p)
{
printf("malloc error !\n");
return NULL;
}
else
{
p->info = x;
top = p;
return top;
}
}
else
{
p = (node_t *)malloc(sizeof(node_t));
if(!p)
{
printf("malloc error !\n");
return NULL;
}
else
{
p->info = x;
p->next = top;
top = p;
return top;
}
}
}
node_t *pop(node_t *top)
{
node_t *p = NULL;
if(!top)
{
printf("no node to pop error!\n");
return NULL;
}
p = top;
top = top->next;
if(p)
{
free(p);
p = NULL;
}
return top;
}
int main(void)
{
node_t *link_stack;
link_stack = init();
//连续给栈推入6个数据
link_stack = push(link_stack,1);
link_stack = push(link_stack,2);
link_stack = push(link_stack,3);
link_stack = push(link_stack,4);
link_stack = push(link_stack,5);
link_stack = push(link_stack,6);
display(link_stack);
//连续推出
printf("pop one node info : %d\n",read(link_stack));
link_stack = pop(link_stack);
display(link_stack);
printf("pop one node info : %d\n",read(link_stack));
link_stack = pop(link_stack);
display(link_stack);
printf("pop one node info : %d\n",read(link_stack));
link_stack = pop(link_stack);
display(link_stack);
printf("push 100 111\n");
link_stack = push(link_stack,100);
link_stack = push(link_stack,111);
display(link_stack);
printf("pop one node info : %d\n",read(link_stack));
link_stack = pop(link_stack);
display(link_stack);
printf("pop one node info : %d\n",read(link_stack));
link_stack = pop(link_stack);
display(link_stack);
printf("pop one node info : %d\n",read(link_stack));
link_stack = pop(link_stack);
display(link_stack);
}
运行结果