单链表堆栈测验括号匹配

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

typedef struct SymbolStack
{
	int symbol;
	struct SymbolStack *next; 
}*pstack;
typedef struct SymbolStack stack;

int IsEmpty(pstack s)
{
	return s->next == NULL;
}

pstack CreateRoot(void)
{
	pstack root;
	root = (pstack)malloc(sizeof(stack));
	root->next = NULL;
    return root;
}

void push(char c, pstack root)
{
	pstack s;
	s = (pstack)malloc(sizeof(stack));
	s->next = root->next;
	s->symbol = c;
	root->next = s;
}

void pop(pstack root)
{
	pstack tmpcell;
	tmpcell = root->next;
	if (tmpcell == NULL)
	{
		printf("Error!");
		return;
	}
	root->next = tmpcell->next;
	free(tmpcell);
}

char top(pstack root)
{
	if (root->next == NULL)
	    return 0;
	else return root->next->symbol;    
}

void BalancingSymbol(void)
{
	char c;
	pstack root = CreateRoot();
	pstack s;
	
	while ((c = getchar()) != EOF)
	{
		/*if anything open*/
		if (c == '(' || c == '{' || c == '[')
		{
		    push(c, root);
		    putchar(c);
		}
		
		/*if anything close*/    
		else
		if (c == ')')
		{
			if (top(root) == c - 1)
            {
            	pop(root);
            	putchar(c);
            }
			else printf("error   "); 
		}
		else
		if (c == '}' || c == ']')
		{
			if (top(root) == c - 2)
			{
				pop(root);
				putchar(c);
			}    
		    else printf("error   ");	
		}
		else putchar(c);		    
	}
	
	/*if at the end of file*/
	if (!IsEmpty(root))
	    printf("error\n");    
}


Make an empty stack. Read characters until end of file. If the character is an opnening symbol, push it onto the stack. If it is a closing symbol, then if the stack is empty report an error. Otherwise, pop the stack. If the symbol popped is not the corresponding opnening symbol, then report an error. At the end of file, if the stack is not empty report an error.





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值