#include <stdio.h>
#include <stdlib.h>
typedef char DataType ;
struct node;//定义一个结点
typedef struct node *PNode; //定义结点指针
struct node{
DataType info;
PNode next;
};
struct stack{//创建一个栈结构体
PNode top;//指向栈顶元素
};
typedef struct stack *Pointstack;
Pointstack createEmpty_stack(void);//无返回值
int ifEmpty_stack(Pointstack Pstack);//传入栈参数
void pushElement_stack(Pointstack pstack,DataType x);
void popElement_stack(Pointstack pstack,DataType x);
DataType ElementStackTop(Pointstack pstack);
//创建一个空栈,返回指向空栈的指针
Pointstack createEmpty_stack(){
Pointstack Pstack=(Pointstack)malloc(sizeof(struct stack));//为结点申请空间
if(Pstack!=NULL){
Pstack->top=NULL;//栈顶赋值为空
}
else{
printf("out of speac");
}
return Pstack;
}
//判断栈是否为空
int ifEmpty_stack(Pointstack pstack){
return (pstack->top?0:1);
}
//往栈中压入一个元素
void pushElement_stack(Pointstack pstack,DataType x){
PNode Snode=(PNode)malloc(sizeof(struct node));//申请一个新的结点空间
if (Snode==NULL)
{
printf("out of speac");
}
else
{
Snode->info=x;
Snode->next=pstack->top;
pstack->top=Snode;
}
//printf("进栈成功\n");
}
//出栈。即删除一个元素
void popElement_stack(Pointstack pstack){
if (ifEmpty_stack(pstack))//判断栈是否已空
{
printf("out of speac");
}
else
{
PNode p=pstack->top;
pstack->top=pstack->top->next;
free(p);
}
}
//求栈顶元素
DataType ElementStackTop(Pointstack pstack){
if (ifEmpty_stack(pstack))
{
printf("stack is empty\n");
exit(0);
}
else
{
return pstack->top->info;
}
}
void main(){
int data;
char ch;
int top;
Pointstack newstack=createEmpty_stack();
printf("输入数字创建栈,以-1结束输入:\n");
scanf("%d",&data);
while(data!=-1){
pushElement_stack(newstack,data);
scanf("%d",&data);
}
printf("\n");
while(!ifEmpty_stack(newstack)){
top=ElementStackTop(newstack);
printf("%d ",top);
popElement_stack(newstack);
}
}
数据结构C 语言描述——实现栈的基本功能
最新推荐文章于 2024-07-25 14:57:29 发布