C语言实现【检测平衡符号】代码+运行结果

目录:

            • 1.题目要求:
            • 2.C语言代码:
            • 3.运行结果:


1.题目要求:

《数据结构与算法分析-C语言描述》[3. 18]

用下列语言编写检测平衡符号的程序:
a.c语言( begin / end , ( ) , [ ] , { } )


2.C语言代码:

文件1:源文件

#include"list.h"

int CharDetect(char c, Stack S){
	int flag=0;
	if (c == 'b'){
		flag = 1;
	}
	else if (c == 'e'){
		flag = 5;
	}
	else if (c == '('){
		Push('(', S);
	}
	else if (c == ')'){
		if (Top(S) == '('){
			Pop(S);
		}
		else{
			printf("缺少'('\n");
		}
	}
	else if (c == '['){
		Push('[', S);
	}
	else if (c == ']'){
		if (Top(S) == '['){
			Pop(S);
		}
		else{
			printf("缺少'['\n");
		}
	}
	else if (c == '{'){
		Push('{', S);
	}
	else if (c == '}'){
		if (Top(S) == '{'){
			Pop(S);
		}
		else{
			printf("缺少'{'\n");
		}
	}
	return flag;
}
int main(){
	Stack S = CreatStack();
	char c;		//char和int类型都可以(不考虑EOF的情况下)
	int flag = 0;
	while ((c = getchar()) != '\n'){	/*‘!=’优先级高于‘=’哦*/
		switch (flag){
		case 0:
			flag = CharDetect(c, S);	
			break;
		case 1:
			if (c == 'e'){
				flag = 2;
			}else{
				flag = CharDetect(c, S);	/*注意若字符不是我们希望的下一个字符,*/
			}						/*不要丢弃,检测此字符有没有可能是其他平衡符号的开头*/
			break;
		case 2:
			if (c == 'g'){
				flag = 3;
			}else{
				flag = CharDetect(c, S);
			}
			break;
		case 3:
			if (c == 'i'){
				flag = 4;
			}else{
				flag = CharDetect(c, S);
			}
			break;
		case 4:
			if (c == 'n'){
				Push('b', S);	/*用字符'b'代替begin五个字符*/
			}
			flag = CharDetect(c, S);
			break;
		case 5:
			if (c == 'n'){
				flag = 6;
			}else{
				flag = CharDetect(c, S);
			}
			break;
		case 6:
			if (c == 'd'){
				if (Top(S) == 'b'){
					Pop(S);
				}
				else{
					printf("缺少'begin'\n");
				}
			}
			flag = CharDetect(c, S);
			break;
		}

	}
	if (S->Next != NULL){
		if (Top(S) == 'b'){
			printf("缺少'end'。\n");
		}
		else{
			printf("没有与%c匹配的符号。\n", Top(S));
		}
	}
	return 0;
}

文件2:list.h

#ifndef _LIST_H

#include
#include

struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode Stack;
typedef PtrToNode Position;
typedef char ElementType;

Stack CreatStack(void);
void Push(ElementType X, Stack S);
void Pop(Stack S);
ElementType Top(Stack S);

#endif


struct Node{
	ElementType Element;
	Position Next;
};

Stack CreatStack(void){
	Stack p = (Stack)malloc(sizeof(struct Node));
	if (!p){
		printf("Out of space!");
	}
	p->Next = NULL;
	return p;
}

void Push(ElementType X, Stack S){
	Position p = (Stack)malloc(sizeof(struct Node));
	if (p){
		p->Element = X;
		p->Next = S->Next;
		S->Next = p;
	}else{
		printf("Out of space!");
	}
	
}

void Pop(Stack S){
	Position p = S->Next;
	if (p){
		S->Next = S->Next->Next;
		free(p);
	}else{
		printf("Empty stack!");
	}
}

ElementType Top(Stack S){
	if (S->Next){
		return S->Next->Element;
	}else{
		return NULL;
	}
}

3.运行结果:

C语言实现【检测平衡符号】代码+运行结果_第1张图片

你可能感兴趣的:(数据结构,算法,c语言,stack)