头文件
#ifndef _LINKSTACK_H_
#define _LINKSTACK_H_
typedef int datatype;
typedef struct Node
{
union
{
datatype data;
int len;
};
struct Node * next;
}Node;
typedef struct
{
Node * top;
}linkstack,*linkstackptr;
//链式栈的创建
linkstackptr stack_create();
//判空
int stack_empty(linkstackptr L);
//入栈
int stack_posh(linkstackptr L,datatype e);
//出栈
int stack_pop(linkstackptr L);
//遍历栈
void stack_show(linkstackptr L);
//释放栈
void stack_free(linkstackptr L);
#endif
ubuntu@ubuntu:linkstack$
源文件
#include"linkstack.h"
#include<stdio.h>
#include<stdlib.h>
//链式栈的创建
linkstackptr stack_create()
{
linkstackptr L=(linkstackptr)malloc(sizeof(linkstack));
if(NULL==L)
{
printf("申请失败\n");
return NULL;
}
L->top=(Node *)malloc(sizeof(Node));
if(NULL==L->top)
{
printf("申请失败\n");
free(L);
return NULL;
}
L->top->len=0;
L->top->next=NULL;
printf("创建成功\n");
return L;
}
//判空
int stack_empty(linkstackptr L)
{
if(NULL==L ||NULL==L->top)
{
printf("所给链表不合法\n");
return -1;
}
return L->top->next==NULL;
}
//入栈
int stack_posh(linkstackptr L,datatype e)
{
if(NULL==L)
{
printf("所给栈不合法\n");
return 0;
}
Node *p=(Node *)malloc(sizeof(Node));
if(NULL==p)
{
printf("入栈失败\n");
return 0;
}
p->data=e;
p->next=L->top->next;
L->top->next=p;
L->top->len++;
printf("入栈成功\n");
return 1;
}
//出栈
int stack_pop(linkstackptr L)
{
if(NULL==L || stack_empty(L))
{
printf("出栈失败\n");
return 0;
}
Node *p=L->top->next;
L->top->next=p->next;
printf("%d出栈成功\n",p->data);
free(p);
p=NULL;
L->top->len--;
return 1;
}
//遍历栈
void stack_show(linkstackptr L)
{
if(NULL==L)
{
printf("遍历失败\n");
return ;
}
Node * p=L->top->next;
while(p->next!=NULL)
{
printf("%d\t",p->data);
p=p->next;
}
printf("%d\n",p->data);
}
//释放栈
void stack_free(linkstackptr L)
{
if(NULL==L )
{
printf("释放失败\n");
return;
}
while(L->top->len=0)
{
stack_pop(L);
}
free(L->top);
L->top=NULL;
free(L);
L=NULL;
printf("销毁成功\n");
}
测试文件
int main(int argc, const char *argv[])
{
linkstackptr L=stack_create();
if(NULL==L)
{
return -1;
}
stack_posh(L,1);
stack_posh(L,2);
stack_posh(L,3);
stack_posh(L,4);
stack_posh(L,5);
stack_show(L);
stack_pop(L);
stack_show(L);
stack_free(L);
return 0;
}