c语言(十七)

栈的应用
1、括号匹配
输入:输入一串字符串str
输出:输出字符串str中的括号是否匹配
优化目标:无

#include<stdio.h>
#define MaxSize 50
 
typedef struct Stack
{
	char data[MaxSize];
	int top;
}Stack,*pStack;
 
void Init_stack(pStack);		//初始化 
int Push(pStack,char);		//入栈
int Pop(pStack);			//出栈
int Check(char *str);			//进行检测 
 
int main()
{
	char str[MaxSize];
	printf("请输入括号组:");
	scanf("%s",str);
	if(Check(str))
		printf("Yes!\n");
	else printf("No!\n");
	
	return 0;
}
 
//初始化 
void Init_stack(pStack ps1)
{
	ps1->top=-1;
}
 
//入栈
int Push(pStack ps1,char e)
{
	if(ps1->top>=MaxSize)
		return 0;
	else
	{
		ps1->data[++ps1->top]=e;
		return 1;
	}
}
 
//出栈
int Pop(pStack ps1)
{
	if(ps1->top<0)
		return 0;
	else
	{
		ps1->top--;
		return 1;
	}
} 
 
//检测
int Check(char *str)
{
	int i=0;
	pStack s1=(pStack)malloc(sizeof(Stack));
	Init_stack(s1);
	while(str[i]!='\0')
	{
		if(str[i]=='('||str[i]=='['||str[i]=='{')
			Push(s1,str[i]);
		else if(str[i]==')'&&s1.data[s1.top]=='('||str[i]==']'&&s1.data[s1.top]=='['||str[i]=='}'&&s1.data[s1.top]=='{')//当前值和栈顶元素匹配,则出栈
			Pop(s1);
		else return 0;
			i++;
	}
	if(s1.top==-1) return 1;//栈为空,则括号匹配成功
	else return 0;
}

2、后缀表达式求值
输入:输入一串字符串str
输出:输出字符串str所表示的后缀表达式的值rst
优化目标:无

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MaxSize 50

typedef int ElemType;
typedef struct node {
	ElemType data;
	struct node *next;
} StackNode;

void InitStack(StackNode **p) {//栈的声明
    (*p)=NULL;
}

int StackEmpty(StackNode *p) {//如果栈是空的返回0;不空返回1
    if(p==NULL)
        return 0;
    return 1;
}

void Push(StackNode **top, ElemType x) {//入栈操作
   StackNode *p;
   p=(StackNode *)malloc(sizeof(StackNode));
   p->data=x;
   p->next=*top;
   *top=p;
}

void Pop(StackNode **top, ElemType *x) {//出栈操作
    StackNode *p;
    if(*top==NULL)
        printf("Stack is empty!\n");
    else{
        *x=(*top)->data;
        p=*top;
        *top=(*top)->next;
        free(p);
    }

}

int Calc(char *s) {
    StackNode *p;
    InitStack(&p);
    ElemType x1,x2;
    int i=0,x;
    while(s[i]!='\0')//进行四则运算
    {
        if(s[i]>='0'&&s[i]<='9')
            Push(&p,s[i]-48);//0的ascii码值是48
        else{
            Pop(&p,&x1);
            Pop(&p,&x2);
            if(s[i]=='+')
                Push(&p,x1+x2);
            if(s[i]=='-')
                Push(&p,x1-x2);
            if(s[i]=='*')
                Push(&p,x1*x2);
            if(s[i]=='/')
                Push(&p,x1/x2);
        }
        i++;
    }
    return p->data;//返回栈顶元素的值
}

int main() {
    char str[MaxSize];
	printf("请输入后缀表达式:");
	scanf("%s",str);
  	int rst;
	rst=Calc(str);
 	printf("the results is: %d\n", rst);
  	return 0;
}

总结:今天练习了栈的应用,加强了对顺序栈、链栈基础知识的掌握。明天计划练习一些c语言题。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值