括号匹配 (栈实现)自动忽略其他字符

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

typedef struct StackNode
{
	char data;
	struct StackNode *next;
}StackNode,*LinkStack;

void Matching(bool *judge);
void push(LinkStack *K,char ch);
bool IsEmpty(LinkStack K);
char GetTop(LinkStack K);
void pop(LinkStack *K);

int main()
{
	bool judge;
	
	Matching(&judge);
	if(judge)
		printf("匹配\n");
	else
		printf("不匹配\n");
}

void Matching(bool *judge)
{
	char ch;
	LinkStack K;
	
    K=NULL;
	*judge=true;
	ch=getchar();	
	while(*judge && ch!='#')
	{
		switch(ch)
		{
			case '(':
			case '[': push(&K,ch);break;   //入栈 
			
			case ')':
		   	  if(GetTop(K)=='(' && !IsEmpty(K))
				pop(&K);
			  else 
			  	*judge=false; break;
			
			case ']':
			  if(GetTop(K)=='[' && !IsEmpty(K))
			  	pop(&K);
			  else 
			  	*judge=false; break;	
		}
		ch=getchar();
	}
}

void push(LinkStack *K,char ch)
{
	StackNode *p;
	
	p=(LinkStack)(malloc(sizeof(StackNode)));
	p->data=ch;
	p->next=*K;
	*K=p;
}

bool IsEmpty(LinkStack K)
{
	if(K)
	return false;
	else
	return true; 
}

char GetTop(LinkStack K)
{
	return K->data;
}

void pop(LinkStack *K)
{
	StackNode *p;
	
	p=*K;
	*K=(*K)->next;
	free(p);
}

猜你喜欢

转载自blog.csdn.net/Huayra221/article/details/81352997
今日推荐