link.stack.h
#ifndef __LINK_STACK__
#define __LINK_STACK__
#include <stdio.h>
#include <stdlib.h>
typedef struct link_stack
{
int data;
struct link_stack *next;
}link_stack,*link_p;
//栈顶指针的类型
//栈顶指针应该独立于栈存在,为了和栈中元素不同
typedef struct top_t
{
int len;
link_p ptop;
}top_t,*top_p;
//申请栈顶指针
top_p create_top();
//申请结点的函数
link_p create_node(int data);
//入栈/压栈
void push_stack(top_p T,int data);
//判空
int empty(top_p T);
//出栈/弹栈
void pop_stack(top_p T);
//输出栈中元素
void show_stack(top_p T);
//销毁
void free_stack(top_p T);
#endif
link_stack.c
#include "link_stack.h"
//申请栈顶指针
top_p create_top()
{
top_p top = (top_p)malloc(sizeof(top_t));
if(top==NULL)
{
printf("空间申请失败\n");
return NULL;
}
top->len = 0;
top->ptop = NULL; //刚申请栈指针时没有指向元素
return top;
}
//申请结点的函数
link_p create_node(int data)
{
link_p new = (link_p)malloc(sizeof(link_stack));
if(new==NULL)
{
printf("申请空间失败\n");
return NULL;
}
new->data = data;
return new;
}
//入栈/压栈
void push_stack(top_p T,int data)
{
if(T==NULL)
{
printf("入参为空\n");
return;
}
link_p new=create_node(data);
new->next=T->ptop;
T->ptop=new;
T->len++;
}
//判空
int empty(top_p T)
{
if(T==NULL)
{
printf("入参为空\n");
return;
}
return T->ptop==NULL?1:0;
}
//出栈/弹栈
void pop_stack(top_p T)
{
if(T==NULL)
{
printf("入参为空\n");
return;
}
if(empty(T))
{
printf("无须出栈\n");
return;
}
link_p p=T;
while(p->next->next!=NULL)
{
p=p->next;
}
link_p del=p->next;
p->next=p->next->next;
free(del);
T->len--;
}
//输出栈中元素
void show_stack(top_p T)
{
if(T==NULL)
{
printf("入参为空\n");
return;
}
if(empty(T))
{
printf("链栈为空\n");
return;
}
link_p p =T->ptop;
while(p!=NULL)
{
printf("%d->",p->data);
p=p->next;
}
printf("NULL\n");
}
//销毁
void free_stack(top_p T)
{
if(T==NULL)
{
printf("入参为空\n");
return;
}
link_p p=T->ptop;
link_p del;
while(p!=NULL)
{
del=p;
p=p->next;
free(del);
del=NULL;
}
}
主程序及其运行结果