本文主要是介绍链栈的代码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
#include "link_stack.h"
//申请栈顶指针
top_p create_top()
{
top_p top=(top_p)malloc(sizeof(top_t));
top->len=0;
top_p ptop=NULL;
}
//申请结点的函数
link_p create_node(int data)
{
link_p new = (link_p)malloc(sizeof(link_stack));
new->data=data;
return new;
}
//入栈/压栈
void push_stack(top_p T,int data)
{
link_p new =create_node(data);
new->next=T->ptop;
T->ptop=new;
T->len++;
}
//判空
int empty(top_p T)
{
return T->ptop==NULL?1:0;
}
//出栈/弹栈
void pop_stack(top_p T)
{
if(!empty(T))
{
link_p del =T->ptop;
if(del->next!=NULL)
{
T->ptop=del->next;
}
free(del);
T->len--;
}
}
//遍历
void show_stack(top_p T)
{
if(T->ptop==NULL)
{
printf("空栈");
}
link_p p =T->ptop;
while(p!=NULL)
{
printf("%d\n",p->data);
p=p->next;
}
}
//释放
void free_stack(top_p T)
{
if(!empty(T))
{
link_p p =T->ptop;
link_p del;
while(p!=NULL)
{
p=del;
p=p->next;
free(del);
}
}
}
#ifndef __LINK_STACK_H__
#define __LINK_STACK_H__
#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_stack * 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
#include "link_stack.h"
int main()
{
top_p T=create_top();
push_stack(T,1);
push_stack(T,2);
push_stack(T,3);
push_stack(T,4);
pop_stack(T);
//free_stack(T);
show_stack(T);
return 0;
}
这篇关于链栈的代码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!