C语言-链栈实现及部分功能
初始化链栈
销毁链栈
清空栈
判断栈是否为空
得到栈顶元素
进栈
出栈
//数据类型
typedef int ElemType;
//定义数据结点
typedef struct node
{
ElemType data;
struct node *next;
struct node *prev;
}Node;
//定义头结点
typedef struct head
{
Node *top;
Node *bottom;
int num;
}Head;
/*
初始化链栈
*/
Head *Init_LinkStack(void)
{
Head *s = (Head *)malloc(sizeof(Head));
s->top = NULL;
s->bottom = NULL;
s->num = 0;
return s;
}
/*
销毁链栈
*/
int DestoryStack(Head *s)
{
if(s == NULL)
{
return 0;
}
Clear_Stack(s);
free(s);
return 1;
}
/*
清空栈
*/
int Clear_Stack(Head *s)
{
if(s == NULL)
{
return 0;
}
Node *p = s->top;
while(p)
{
s->top = p->prev;
p->prev = NULL;
(s->top) ? (s->top->next = NULL) : NULL;
free(p);
p = s->top;
}
s->num = 0;
return 1;
}
/*
判断栈为空
为空返回1,不为空返回0
*/
int StackEmpty(Head *s)
{
if(s == NULL || s->num == 0)
{
return 1;
}
else
{
return 0;
}
}
/*
得到栈中元素个数
*/
int StackLenth(Head *s)
{
return s->num;
}
/*
得到栈顶元素
*/
int GetStack(Head *s, ElemType *e)
{
if(s == NULL || s->num ==0)
{
return 0;
}
*e = s->top->data;
return 1;
}
/*
进栈
*/
int Push(Head *s, ElemType e)
{
if(s == NULL)
{
return 0;
}
Node *p = (Node *)malloc(sizeof(Node));
p->data = e;
p->next = p->prev = NULL;
if(s->num == 0)
{
s->bottom = s->top = p;
}
else
{
s->top->next = p;
p->prev = s->top;
s->top = p;
}
s->num++;
return 1;
}
/*
出栈
*/
int Pop(Head *s, ElemType *e)
{
if(s == NULL || StackEmpty(s))
{
return 0;
}
Node *p = s->top;
s->top = p->prev;
(s->top) ? (s->top->next = NULL) : NULL;
p->prev = NULL;
*e = p->data
free(p);
s->num--;
return 1;
}