1.带头结点:
#include<stdio.h>
#include<stdlib.h>
#define ElemType int
//基本数据类型:
typedef struct LinkNode{
ElemType data;
struct LinkNode* next;
}LinkNode,*LinkStack;
//初始化链栈:
bool InitLinkStack(LinkStack &S)
{
S=(LinkStack)malloc(sizeof(LinkNode));
S->next=NULL;
return true;
}
//判断链栈是否为空栈:
bool LinkStackEmpty(LinkStack S)
{
if(S->next)return false;
else return true;
}
//链栈的入栈操作:
bool Push(LinkStack &S,ElemType x)
{
if(x!=9999)
{
LinkNode *r=(LinkNode*)malloc(sizeof(LinkNode));
r->data=x;
r->next=S->next;
S->next=r;
return true;
}
else return false;
}
//获取链栈的栈顶元素,但不做出栈操作
bool GetTop(LinkStack S,ElemType &x)
{
if(S->next==NULL)return false;
x=S->next->data;
return true;
}
//链栈的出栈操作
bool Pop(LinkStack &S,ElemType &x)
{
LinkNode *p;
if(S->next==NULL)return false;
p=S->next;
x=p->data;
S->next=p->next;
free(p);
return true;
}
int main()
{
ElemType x;
//声明一个链栈:
LinkStack S;
//链栈初始化:
InitLinkStack(S);
if(LinkStackEmpty(S))printf("\n此链栈是空的\n");
else printf("\n此链栈不空\n");
printf("\n开始向链栈中输入数据:\n");
while(1)
{
scanf("%d",&x);
if(x==9999)
{
printf("\n输入结束\n");
break;
}
if(Push(S,x))printf("\n成功插入\n");
}
if(GetTop(S,x))printf("\n栈顶元素为: %d\n",x);
printf("\n元素依次出栈:\n");
while(Pop(S,x))printf("%d ",x);
printf("\n");
}
2.不带头结点:
#include<stdio.h>
#include<stdlib.h>
#define ElemType int
//基本数据类型:
typedef struct LinkNode{
ElemType data;
struct LinkNode* next;
}LinkNode,*LinkStack;
//初始化链栈:
bool InitLinkStack(LinkStack &S)
{
S=NULL;
return true;
}
//判断链栈是否为空栈:
bool LinkStackEmpty(LinkStack S)
{
if(S)return false;
else return true;
}
//链栈的入栈操作:
bool Push(LinkStack &S,ElemType x)
{
if(x!=9999)
{
LinkNode *r=(LinkNode*)malloc(sizeof(LinkNode));
r->data=x;
r->next=S;
S=r;
return true;
}
else return false;
}
//获取链栈的栈顶元素,但不做出栈操作
bool GetTop(LinkStack S,ElemType &x)
{
if(S==NULL)return false;
x=S->data;
return true;
}
//链栈的出栈操作
bool Pop(LinkStack &S,ElemType &x)
{
LinkNode *p;
if(S==NULL)return false;
p=S;
x=p->data;
S=p->next;
free(p);
return true;
}
int main()
{
ElemType x;
//声明一个链栈:
LinkStack S;
//链栈初始化:
InitLinkStack(S);
if(LinkStackEmpty(S))printf("\n此链栈是空的\n");
else printf("\n此链栈不空\n");
printf("\n开始向链栈中输入数据:\n");
while(1)
{
scanf("%d",&x);
if(x==9999)
{
printf("\n输入结束\n");
break;
}
if(Push(S,x))printf("\n成功插入\n");
}
if(GetTop(S,x))printf("\n栈顶元素为: %d\n",x);
printf("\n元素依次出栈:\n");
while(Pop(S,x))printf("%d ",x);
printf("\n");
}