1.头文件
#ifndef __LINK_STACK_H__
#define __LINK_STACK_H__
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}node,*node_p;
node_p create_node(int data);
void push_stack(node_p *T,int data);
int empty_stack(node_p T);
void pop_stack(node_p *T);
void show(node_p T);
#endif
2.自定义函数
#include "link_stack.h"
//申请节点
node_p create_node(int data)
{
node_p H=(node_p)malloc(sizeof(node));
if(H==NULL)
{
printf("空间申请失败\n");
return NULL;
}
H->data=data;
return H;
}
//入栈
//传入二级指针,为了改变外部指针变量
void push_stack(node_p *T,int data)
{
node_p new=create_node(data);
new->next = *T;
*T = new;
}
//判空
int empty_stack(node_p T)
{
return T==NULL?1:0;
}
//出栈
void pop_stack(node_p *T)
{
if(*T==NULL)
{
printf("栈为空,无需出栈\n");
return;
}
node_p w= *T;
*T = (*T)->next;
free(w);
}
//输出栈
void show(node_p T)
{
if(T==NULL)
{
printf("栈为空,无需输出\n");
return;
}
node_p temp=T;
while(temp!=NULL)
{
printf("%d\n",temp->data);
temp=temp->next;
}
}
3.主函数
#include"link_stack.h"
int main()
{
node_p T=NULL;
push_stack(&T,100);
push_stack(&T,90);
push_stack(&T,80);
pop_stack(&T);
show(T);
return 0;
}