#ifndef _LINKSTACK_H_
#define _LINKSTACK_H_
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef int datatype;
typedef struct Node
{
union
{
int len;
datatype data;
};
struct Node * next;
}Node;
typedef struct
{
Node* Base;
Node* Top;
}LinkStack, *LinkStackPtr;
//创建链式栈
LinkStackPtr stack_create();
//判空
int stack_empty(LinkStackPtr s);
//头插
int stack_push(LinkStackPtr s,datatype e);
//头删
int stack_delete_head(LinkStackPtr s);
//尾插
int stack_push_tail(LinkStackPtr s,datatype e);
//尾删
int stack_delete_tail(LinkStackPtr s);
//遍历
void stack_show(LinkStackPtr s);
//销毁
void stack_free(LinkStackPtr s);
#endif
#include"linkstack.h"
//创建链式栈
LinkStackPtr stack_create()
{
LinkStackPtr s = (LinkStackPtr)malloc(sizeof(LinkStack));
if(NULL == s)
{
printf("创建失败\n");
return NULL;
}
s -> Top = (Node*)malloc(sizeof(Node));
if(NULL == s -> Top)
{
printf("创建失败\n");
return NULL;
}
s -> Top -> len = 0;
s -> Base = s -> Top = NULL;
return s;
}
//判空
int stack_empty(LinkStackPtr s)
{
if(NULL == s)
{
printf("栈不合法\n");
return 0;
}
return s -> Base == s -> Top;
}
//头插
int stack_push(LinkStackPtr s,datatype e)
{
if(NULL == s)
{
printf("入栈失败\n");
return 0;
}
Node *p =(Node*)malloc(sizeof(Node));
if(NULL == p)
{
return 0;
}
p -> next = NULL;
p -> data = e;
p -> next = s -> Top;
s -> Top = p;
printf("头插成功\n");
return 1;
}
//头删
int stack_delete_head(LinkStackPtr s)
{
if(NULL == s || stack_empty(s))
{
printf("头删失败\n");
}
Node *p = NULL;
p = s -> Top;
s -> Top = p -> next;
free(p);
p = NULL;
printf("头删成功\n");
return 1;
}
/*
//尾插
int stack_push_tail(LinkStackPtr s,datatype e)
{
if(NULL == s)
{
printf("尾插失败\n");
return 0;
}
while(s -> Top -> next != NULL)
{
s -> Top = s -> Top -> next;
}
Node *p =(Node*)malloc(sizeof(Node));
if(NULL == p)
{
return 0;
}
p -> next = NULL;
p -> data = e;
s -> Top -> next = p;
s -> Top -> len++;
printf("尾插成功\n");
return 1;
}
//尾删
int stack_delete_tail(LinkStackPtr s)
{
if(NULL == s || stack_empty(s))
{
printf("尾删失败\n");
return 0;
}
while(s -> Top -> next -> next != NULL)
{
s -> Top = s -> Top -> next;
}
LinkStackPtr p;
p -> Top = s -> Top;
s -> Top -> next = NULL;
free(p -> Top -> next);
p -> Top -> next = NULL;
printf("尾删成功\n");
return 1;
}
*/
//遍历
void stack_show(LinkStackPtr s)
{
if(NULL == s || stack_empty(s))
{
printf("遍历失败\n");
return ;
}
Node* p = s -> Top;
while(s -> Base != p)
{
printf("%d\t",p -> data);
p = p -> next;
}
printf("\n");
}
//销毁
void stack_free(LinkStackPtr s)
{
if(NULL == s)
{
printf("销毁失败\n");
return ;
}
free(s -> Top);
s -> Top = NULL;
free(s -> Base);
s -> Base = NULL;
free(s);
s = NULL;
printf("销毁成功\n");
}