【锐格】数据结构-栈-表达式配对问题

6110

具体为何记录,待补充

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>

#define TRUE 1
#define FALSE 0
#define s top

typedef int Status;

typedef struct Node
{
    char data;
    struct Node *next;
}Node;

Node *top;

const Status isEmpty()
{
    return (top==NULL)?TRUE:FALSE;
}

void Push(const char x)
{
    Node *n = (struct Node *)malloc(sizeof(struct Node));
	n->data = x;
	n->next = top;
	top = n;
}

void PrintList()
{
    printf("-------");
    Node *p=top;
    while(p!=NULL)
    {
        printf("%c ", p->data);
        p=p->next;
    }
    printf("\n");
}

Status Pop(char *x)
{
	if (isEmpty())
		return FALSE;
	*x = top->data;
	Node *t = top;
	top = top->next;
	free(t);
	return TRUE;
}

Status getTop(char &x)
{
	if (isEmpty())
		return FALSE;
	x = top->data;
	return TRUE;
}

Status match(char f[]) {
	char* p = f;
	char ch;
	int stats=0;
	while (*p != '\0') {
		if (*p == 39) {//单引号
			++p;
			while (*p != 39)//小括号
				++p;
			++p;
		}
		else if (*p == 34) {//双引号
			++p;
			while (*p != 34)//小括号
				++p;
			++p;
		}
		else {
			switch (*p) {
			case '(':Push(*p); break;
			case '{':Push(*p); break;
			case '[':Push(*p); break;
			case ')':stats=getTop(ch);
			//printf("%c %c\n",*p, ch);
			//PrintList();
				if (ch == '(' && stats==1)
                {
                    Pop(&ch);
                }

				else return 0;
				break;
			case '}':stats=getTop(ch);
			//printf("%c %c\n",*p, ch);
			//PrintList();
				if (ch == '{' && stats==1)
                {
                    Pop(&ch);
					getTop(ch);
                }
				else return 0;
				break;
			case ']':stats=getTop(ch);
			//printf("%c %c\n",*p, ch);
			//PrintList();
				if (ch == '[' && stats==1)
                {
                    Pop(&ch);
					getTop(ch);
                }
				else return 0;
			}
			++p;
		}
	}
	if (isEmpty())//如果栈为空,表示括号都已经匹配
		return 1;
	else
		return 0;
}

int main()
{
	top = NULL;
	char str[100];
	int i=0;
	while(scanf("%c", &str[i])!=EOF && str[i]!='#') i++;
	str[i]='\0';
	if (match(str))
		printf("1\n");
	else
		printf("0\n");
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值