1.整理链表的代码
link.stack.h文件
#ifndef __LINK_STACK_H__
#define __LINK_STACK_H__
#include<stdio.h>
#include<stdlib.h>
typedef int datatype;
typedef struct link_stack
{
datatype data;
struct link_stack *next;
}link_stack,*link_p;
typedef struct top_t
{
int len;
link_p ptop;
}top_t,*top_p;
//申请栈顶
top_p creat_top();
//申请结点的函数
link_p creat_nod(int data);
//判空
int empty(top_p T);
//入栈/压栈
void push_stack(top_p T,int data);
//出栈
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 creat_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 creat_nod(int data)
{
link_p new = (link_p)malloc(sizeof(link_stack));
if(new==NULL)
{
printf("申请空间失败\n");
return NULL;
}
new->data = data;
return new;
}
//判空
int empty(top_p T)
{
if(T==NULL)
{
printf("入参失败\n");
return -1;
}
return T->ptop==NULL?1:0;
}
//入栈/压栈
void push_stack(top_p T,int data)
{
if(T==NULL)
{
printf("入参为空\n");
return;
}
link_p new = creat_nod(data);
new->next = T->ptop;
T->ptop = new;
T->len++;
}
//出栈
void pop_stack(top_p T)
{
if(T==NULL)
{
printf("入参为空\n");
return;
}
if(empty(T))
{
printf("栈为空\n");
return;
}
link_p pop = T->ptop;
T->ptop = T->ptop->next;
printf("出栈的元素为:%d\n",pop->data);
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;
for(int i=T->len;i>=1;i--)
{
printf("%d\n",p->data);
if(p->next!=NULL)
{
p = p->next;
}
}
}
//销毁
void free_stack(top_p *T)
{
link_p p = (*T)->ptop;
while(p!=NULL)
{
link_p q = p->next;
free(p);
p = q;
}
free(*T);
*T = NULL;
}
main.c文件
#include "link_stack.h"
int main()
{
top_p T = creat_top();
push_stack(T,1);
push_stack(T,2);
push_stack(T,3);
pop_stack(T);
pop_stack(T);
printf("%d\n",empty(T));
show_stack(T);
free_stack(&T);
show_stack(T);
return 0;
}