栈及其简单应用

//栈是一种特殊的线性表
//是一种先进后出表(FILO),只有栈顶元素才能被操作
//特殊:栈具有特殊的存储访问结构
如图
//栈的操作:入栈:向栈中存储数据元素(push)
出栈:从栈中取出元素(pop)
//栈顶指针(top):用来指向最后一个入栈元素
//栈满(上溢)不可入栈(top==size-1)
//入栈操作:top=top+1; s【top】=数据元素; 即s【++top】=数据元素;
//出栈操作:if(栈不空){出栈}
//栈空条件 top!=-1 s【top–】

//栈的简单应用
//任意输入一个正整数x,输出x的二进制数

#include<stdio.h>
#include<stdlib.h>
#define SIZE 100
int ExchangeBin(int *s,int x)
{
	int top=-1;
	while(x){
		if(top!=SIZE-1){//判断栈是否存满 
			s[++top]=x%2;
			x=x/2;
		}
		else{
			printf("栈满无法存入!");
		}
	}
	return top;
}
void PrintBin(int *s,int top)
{
	while(top!=-1){//栈不空 出栈 
		printf("%d",s[top--]);
	}
}
int main()
{
	int *s;//指向栈空间
	int x,top;
	//定义栈空间
	s=(int *)malloc(SIZE*sizeof(int));
	//输入正整数
	printf("请输入一个正整数:");
	scanf("%d",&x);
	//转换二进制
	top=ExchangeBin(s,x);
	//输出
	PrintBin(s,top);
	top=-1;
	free(s);
	return 0; 
}

//判断一个数学表达式的左右括号是否匹配
//逻辑上有一个栈,只是通过栈顶指针记录

#include<stdio.h>
#include<stdlib.h>
#define Max 50
int Judge(char *s,int top)
{
	int i=0;
	while(s[i]){
		if(top!=Max-1){
		if(s[i]=='('){
			top++;
		}
		if(s[i]==')'){
			top--;
		} 
	}
		else{
			printf("栈的空间不足");
		 break; 
	}
	i++;
	} 
	int x=0;
	top==-1?x=1:x=0;
	return x;
}
int main()
{
	char *s;
	int t;
	int top=-1;
	s=(char *)malloc(Max*sizeof(char));
	printf("please input the char of s:");
	gets(s);
	t=Judge(s,top);
	free(s); 
	if(t==1){
	printf("匹配");
	}
	else{
	printf("不匹配");	
	}
}

猜你喜欢

转载自blog.csdn.net/qq_42727102/article/details/89007645