您的位置:首页 > 其它

链栈的定义及相关操作

2017-05-20 18:31 204 查看
#include <stdio.h>
#include <malloc.h>
typedef int ElemType;

typedef struct linknode
{
ElemType data;
linknode *next;
} Node,*LinkStack;

void PrintStack(LinkStack top);//打印栈中的元素
void DestroyStack(LinkStack top);//销毁栈
bool Push(LinkStack top,ElemType x);//压栈
bool Pop(LinkStack top,ElemType *x);//出栈
bool IsEmpty(LinkStack top);//判断栈空
int StackTop(LinkStack top);//返回栈顶元素
int StackLen(LinkStack top);//求栈中元素的个数

int main(void)
{
int x;
int *a=&x;
LinkStack S1=(LinkStack)malloc(sizeof(Node));
S1->next=NULL;
for(int i=1; i<=10; i++)
Push(S1,i);
printf("%d\n",StackLen(S1));
PrintStack(S1);
Pop(S1,a);
printf("%d\n",x);
if(!IsEmpty(S1))
printf("NO\n");
printf("%d\n",StackTop(S1));
printf("%d\n",StackLen(S1));
DestroyStack(S1);
return 0;
}

void PrintStack(LinkStack top)//打印栈中的元素
{
if(top->next==NULL)
printf("the stack is empty\n");
else
{
while(top->next!=NULL)
{
printf("%d ",top->next->data);
top=top->next;
}
printf("\n");
}
}

void DestroyStack(LinkStack top)//销毁栈
{
LinkStack q;
while(top)
{
q=top->next;
delete top;
top=q;
}
printf("销毁成功");
}

bool Push(LinkStack top,ElemType x)//压栈
{
Node *p;
p=(LinkStack)malloc(sizeof(Node));
if(p==NULL)
return false;
p->data=x;
p->next=top->next;
top->next=p;
return true;
}

bool Pop(LinkStack top,ElemType *x)//出栈
{
Node *p;
p=top->next;
if(p==NULL)
return false;
top->next=p->next;
*x=p->data;
free(p);
return true;
}

bool IsEmpty(LinkStack top)//判断栈空
{
if(top->next==NULL)
return true;
else
return false;
}

int StackTop(LinkStack top)//返回栈顶元素
{
if(top->next==NULL)
printf("the Stack is empty\n");
return top->next->data;
}

int StackLen(LinkStack top)//求栈中元素的个数
{
int len=0;
while(top->next!=NULL)
{
len++;
top=top->next;
}
return len;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: