stack.h
#pragma once
#define MAX_STACKS 10
typedef struct {
int key;
}element;
typedef struct stack *stackPointer;
typedef struct stack {
element data;
stackPointer link;
};
void createStack(int i);
int isEmpty(int i);
int isFull(int i);
void push(int i, element item);
element pop(int i);
Matching.cpp
#include<stdio.h>
#include<string.h>
#include "stack.h"
stackPointer top[MAX_STACKS];
int matching(char s[])
{
int len = strlen(s);
createStack(0);
element item;
for (int i = 0; i < len; i++) {
if (s[i] == '(') {
item.key = s[i];
push(0, item);
}
else if (s[i] == ')') {
if (isEmpty(0)) {
return 0;
}
pop(0);
}
}
if (isEmpty(0)) {
return 1;
}
else {
while (!isEmpty(0))
{
pop(0);
}
return 0;
}
}
int main()
{
char str[100];
printf("Please input the expression :");
gets_s(str);
while (str[0] != 0) {
printf("The bracket of the expression is matching ");
if (matching(str)) {
printf("OK!\n");
}
else {
printf("ERROR!\n");
}
printf("Please input the expression :");
memset(str, 0, sizeof(str));
gets_s(str);
}
}
Stack.cpp
#include "stack.h"
#include<stdio.h>
#include<stdlib.h>
#define MALLOC(p,s)\
if(!((p)=(stackPointer)malloc(s))){\
fprintf(stderr,"Insufficient memory");\
exit(EXIT_FAILURE);\
}
extern stackPointer top[MAX_STACKS];
void createStack(int i)
{
top[i] = NULL;
}
int isEmpty(int i)
{
return top[i] == NULL;
}
int isFull(int i)
{
return 0;
}
void push(int i, element item)
{
stackPointer temp;
MALLOC(temp, sizeof(*temp));
temp->data = item;
temp->link = top[i];
top[i] = temp;
}
element stackEmpty()
{
element item;
item.key = -1;
return item;
}
element pop(int i)
{
stackPointer temp = top[i];
element item;
if (isEmpty(i))
return stackEmpty();
item = temp->data;
top[i] = temp->link;
free(temp);
return item;
}
括号匹配
最新推荐文章于 2022-05-10 22:49:32 发布