张三_李四

为一件事而拼命努力

栈的括号匹配 C语言

//括号匹配
#define ElementType char
struct StackNode
{
	ElementType data;
	int Length;
	struct StackNode* pNext;
};
typedef struct StackNode *Stack;

Stack CreateStack()
{
	Stack MyStack = (Stack)malloc(sizeof(struct StackNode));
	MyStack->pNext = NULL;
	MyStack->Length = 0;
	return MyStack;
}


void Push(Stack S,ElementType data)
{
	Stack TmpCell = (Stack)malloc(sizeof(struct StackNode));
	TmpCell->data = data;
	TmpCell->pNext = S->pNext;
	S->pNext = TmpCell;
}

ElementType Pop(Stack S)
{
	if (S->pNext==NULL)
	{
		printf("Empty\n");
		exit(0);
	}
	Stack Temp;
	Temp = S->pNext;
	S->pNext = Temp->pNext;
	ElementType T = Temp->data;
	free(Temp);
	return T;
}
ElementType GetTop(Stack S)
{
	if (!S->pNext)
	{
		printf("Empty\n");
		exit(0);
	}
	Stack Temp;
	Temp = S->pNext;
	ElementType T = Temp->data;
	return T;
}

int main()
{
    	Stack S1 = CreateStack();
	char ch[20];
	printf("请输入括号个数:\n");
	int n = 0;
	scanf("%d", &n);
	printf("请输入表达式\n");
	scanf("%s", ch);
	int i = 0;
	char need;
	int flag = 0;
	for (i; i < n;i++)
	{
		switch (ch[i])
		{
		case '[':
		{
			need = ']';
			Push(S1, need);
			S1->Length++;
			break;
		}
		case '(':
		{
			need = ')';
			Push(S1, need);
			S1->Length++;
			break;
		}
		case ']':
		    {
				if (GetTop(S1) == ']')
				{
					ElementType T = Pop(S1);
					S1->Length--;
				}
				else
				{
					flag = 1;
				}
			        break;
		    }
		case ')':
		    {
				if (GetTop(S1) == ')')
				{
					ElementType T = Pop(S1);
					S1->Length--;
				}
				else
				{
					flag = 1;
				}
				break;
		    }
		default:
		    {
				  flag = 1;
			      break;
		    }
		}
	}
	if (S1->Length==0&&flag==0)
		printf("匹配成功\n");
	else
		printf("不匹配\n");
}

阅读更多
版权声明: https://blog.csdn.net/qq_41750725/article/details/79947375
上一篇快速排序 C语言
下一篇一元多项式的相加
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭