ikun课堂--顺序栈的基本操作(C语言)

定义栈

typedef struct
{  
    int a[Size];
	int top;
}Stack;

初始化栈

void InitStack(Stack *S)//初始化栈 
{
	S->top=-1;
}

判空

void Empty(Stack A)//判空 
{
   	if(A.top==-1)
   	{
   		printf("Empty.\n");
   	}
   	else
   	    printf("Not empty\n");
} 

进栈

void Push(Stack *S)//进栈 
{
	int x;
	 while(S->top!=Size-1)
	{
		printf("Stack is not full,please input number:\n");
        scanf("%d",&x);
        S->a[S->top++]=x;    
	}	   
}

出栈

int Pop(Stack *S)//出栈 
{
	int x;
	if(S->top!=-1)
	{
		x=S->a[S->top--];
	}
	else
	   printf("The Stack is empty.\n");
	   return x;
}

读取栈顶元素

void Gettop(Stack *S)//读取栈顶元素
{
	int x;
	if(S->top!=-1)
	{
		x=S->a[S->top];
	    printf("栈顶元素为:%d\n",x);
	}
	else 
	    printf("The Stack is empty.\n");

}

销毁栈

void Destory(Stack *S)//销毁栈
{
	S->top=-1;
}

在这里插入图片描述
在下附上完整代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define Size 3
typedef struct
{
	int a[Size];
	int top;
}Stack;
void InitStack(Stack *A);//初始化栈 
void Empty(Stack A); //判空 
void Push(Stack *S);//进栈 
void Pop(Stack *S);//出栈 
void Gettop(Stack *S);//读取栈顶元素
void Destory(Stack *S);//销毁栈
int main()
{
	Stack A;
	int x;
	InitStack(&A);//初始化栈
	Empty(A); //判空 
	Push(&A);//进栈 
	Gettop(&A);//读取栈顶元素
	x=Pop(&A);//出栈 
	Destory(&A);
	printf("S->top=%d\n",A.top);
	Empty(A);
	return 0;
}
void InitStack(Stack *S)//初始化栈 
{
	S->top=-1;
}
void Empty(Stack A)//判空 
{
   	if(A.top==-1)
   	{
   		printf("Empty.\n");
   	}
   	else
   	    printf("Not empty\n");
} 
void Push(Stack *S)//进栈 
{
	int x;
	 while(S->top!=Size-1)
	{
		printf("Stack is not full,please input number:\n");
        scanf("%d",&x);
        S->a[S->top++]=x;
       
	}	   
}
int Pop(Stack *S)//出栈 
{
	int x;
	if(S->top!=-1)
	{
		x=S->a[S->top--];
	}
	else
	   printf("The Stack is empty.\n");
	   return x;
}
void Gettop(Stack *S)//读取栈顶元素
{
	int x;
	if(S->top!=-1)
	{
		x=S->a[S->top];
	    printf("栈顶元素为:%d\n",x);
	}
	else 
	    printf("The Stack is empty.\n");

}
void Destory(Stack *S)//销毁栈
{
	S->top=-1;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值