PTA 6-11 括号匹配(数据结构)

本题要求通过栈来判断括号匹配问题,如果匹配输出yes!,否则输出no!

函数接口定义:

void BracketMatch(LinkStack top)

其中,top是栈顶

裁判测试程序样例:

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

typedef int DataType;
struct Node {
    DataType      data;
    struct Node*  next;
};
typedef struct Node  *PNode;
typedef struct Node  *LinkStack;

LinkStack SetNullStack_Link()  
{
    LinkStack top = (LinkStack)malloc(sizeof(struct Node));
    if (top != NULL) top->next = NULL;
    else printf("Alloc failure");
    return top;  
}

int IsNullStack_link(LinkStack top) 
{
    if (top->next == NULL)
        return 1;
    else
        return 0;
}

void Push_link(LinkStack top, DataType x) 
{
    PNode p;
    p = (PNode)malloc(sizeof(struct Node));
    if (p == NULL)
        printf("Alloc failure");
    else
    {
        p->data = x;
        p->next = top->next;
        top->next = p;
    }
}
void Pop_link(LinkStack top)
{
    PNode p;
    if (top->next == NULL)
        printf("it is empty stack!");
    else
    {
        p = top->next;
        top->next = p->next;
        free(p);
    }
}
DataType Top_link(LinkStack top)
{
    if (top->next == NULL)
    {
        printf("It is empty stack!");
        return 0;
    }
    else
        return top->next->data;
}

void BracketMatch(LinkStack top)
{
    @@
}
int main()
{
    LinkStack mystack = NULL;
    mystack = SetNullStack_Link();
    BracketMatch(mystack);
    return 0;
}

输入样例:

(())#

输出样例:

yes!

输入样例:

(()#

输出样例:

no!

代码实现(C语言)

void BracketMatch(LinkStack top)
{
    
    char str,str1;
    int flag=0;
    
	scanf("%c",&str);
	
	if(str=='(')
	{
		Push_link(top, str); 
		flag++;
	}
	else
	{
		printf("no!\n");
		exit(0);
	}
	
	while(str!='#')
	{
		scanf("%c",&str);
        
		if(str==')')
		{
			str1=Top_link(top);
			Pop_link(top);
            
			if(str1=='('&&str==')')
				flag--;
			else
			{
				printf("no!\n");
				exit(0);	
			}	
		}
		else if(str=='(')
		{
			Push_link(top,str); 
			flag++;
		}
	}
    
	if(flag==0)
		printf("yes!\n");
	else
		printf("no!\n");	
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值