#include <stdio.h>
#include <stdbool.h>
#include <malloc.h>
typedef int ElemType;
//定义链栈节点结构
typedef struct StackNode
{
ElemType data;
struct StackNode *next;
}*PStackNode,StackNode;
//定义头指针
typedef struct HeadLink
{
PStackNode top;
int count;
}LinkStack;
//初始化链栈
bool initstack(LinkStack *L)
{
L->top=(PStackNode)malloc(sizeof(StackNode));
if(!L->top)
{
return false;
}
L->top=NULL;
L->count=0;
return true;
}
//判断链栈是否为空
bool isEmpty(LinkStack* L)
{
if(L->count==0)
{
return true;
}
return false;
}
//清空链栈
bool ClearStack(LinkStack *L)
{
PStackNode p,q;
p=L->top;
while(p)
{
q=p;
p=p->next;
free(q);
}
L->count=0;
return true;
}
//获取链栈长度
int GetLengh(LinkStack *L)
{
return L->count;
}
//入栈
bool Push(LinkStack *L,ElemType e)
{
PStackNode p=(PStackNode)malloc(sizeof(StackNode));
p->data=e;
p->next=L->top;
L->top=p;
L->count++;
return true;
}
//出栈
bool Pop(LinkStack *L)
{
PStackNode p;
if(isEmpty(L))
{
printf("kong\n");
return false;
}
p=L->top;
L->top=p->next;
free(p);
L->count--;
return true;
}
//获取链栈栈顶元素
int GetTop(LinkStack *L)
{
if(isEmpty(L))
{
printf("kong");
return 0;
}
return L->top->data;
}
//链栈的打印
bool PrintStack(LinkStack *L)
{
if(isEmpty(L))
{
printf("Kong\n");
return false;
}
PStackNode p;
p=L->top;
while (p!=NULL)
{
printf("%d\t",p->data);
p=p->next;
}
printf("\n");
return true;
}
int main()
{
LinkStack L;
initstack(&L);
for(int i=0;i<5;i++)
{
Push(&L,i);
}
PrintStack(&L);
printf("%d\n",GetTop(&L));
ClearStack(&L);
PrintStack(&L);
return 0;
}
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交