摘要:链式栈 首先它是链式的,需要用malloc在堆区开辟空间,所以相对于顺序栈来说,就很节省空间,其次,栈的特点是先进后出(FILO),它与队列是相反的操作。就像装子弹,先进去的子弹总是最后打出来。
实现函数:linkstack.c
#include#include #include #include #include "linkstack.h" Linkstack *Create_Link() //创建头节点 { Linkstack *head =(Linkstack *)malloc(sizeof(Linkstack)); if(NULL == head){ printf("head is NULLn"); return NULL; } head->next=NULL; head->data=-1; return head; } int Linkstack_Is_Empty(Linkstack *head)//判空 { if(head->next == NULL){ return 0; } return 1; } int Linkstack_Lenth(Linkstack *head)//计算表长 { Linkstack *p; int i=0; p=head->next; while(p!= NULL){ i++; p=p->next; } return i; } void Linkstack_posh(Linkstack *head,data_t data)//入栈 { Linkstack *new =(Linkstack *)malloc(sizeof(Linkstack)); if(NULL == new){ printf("new is NULLn"); return; } new->data=data; new->next=NULL; new->next=head->next; head->next=new; } void Linkstack_pop(Linkstack *head,data_t *data){//出栈 if(Linkstack_Is_Empty(head)==0){ printf("stack is nulln"); return; } Linkstack *p=head->next; head->next=p->next; *data=p->data; free(p); p=NULL; }
头文件(函数声明):linkstack.h
#ifndef _LINKSTACK_H
#define _LINKSTACK_H
typedef int data_t;
typedef struct linkstack{
data_t data;
struct linkstack *next;
}Linkstack;
Linkstack *Create_Link();
void Linkstack_posh(Linkstack *head,data_t data);//从表头插入数据
int Linkstack_Lenth(Linkstack *head);//计算表长
void Linkstack_pop(Linkstack *head,data_t *data);//pop
int Linkstack_Is_Empty(Linkstack *head);//判空
#endif
主函数:main.c
#include#include #include #include #include "linkstack.h" int main(){ Linkstack *head=Create_Link(); int n=10; while(n--){ Linkstack_posh(head,n);//从表头插入数据 } int data=0; while(head->next!=NULL){ Linkstack_pop(head,&data); printf("%d ",data); } puts(" "); return 0; }
好!今天的分享到此结束,哪里写的不对的,请各位大佬多多指正,不吝赐教,谢谢!(只因你太美)



