1.c
#include"1.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_p));
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 link_empty(top_p T)
{
if(T==NULL)
{
printf("入参为空\n");
return 2;
}
return T->ptop==NULL?1:0;
}
//出栈/弹栈
void pop_stack(top_p T)
{
if(T==NULL)
{
printf("入参为空\n");
return;
}
link_p new=T->ptop;
T->ptop=new->next;
free(new);
T->len--;
}
//遍历
void show_stack(top_p T)
{
if(T==NULL)
{
printf("入参为空\n");
return;
}
if(link_empty(T))
{
printf("栈为空\n");
return;
}
link_p new=T->ptop;
while(new!=NULL)
{
printf("%d->",new->data);
new=new->next;
}
printf("%s","NULL");
putchar(10);
}
//销毁
void free_stack(top_p T)
{
if(T==NULL)
{
printf("入参为空\n");
return;
}
//释放堆区空间
link_p p = T->ptop;
while (p != NULL)
{
link_p new = p->next;
free(p);
p = new;
}
// 释放栈顶结构体的内存
free(T);
T = NULL;
}
1.h
#ifndef __1_H_
#define __1_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_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 link_empty(top_p T);
void pop_stack(top_p T);
void show_stack(top_p T);
void free_stack(top_p T);
#endif
main .c
#include"1.h"
int main()
{
top_p T=create_top();
push_stack(T,23);
push_stack(T,45);
push_stack(T,67);
push_stack(T,68);
push_stack(T,88);
show_stack(T);
pop_stack(T);
show_stack(T);
free_stack(T);
}