考研复习下栈结构
#include<stdio.h>//标准输入输出流(scanf_s,printf函数)
#include<stdlib.h>//(malloc动态申请内存函数)
#include<string.h>//(strlen函数获取字符串长度)
#include<stdbool.h>//(C语言时没有bool类型,如果用c++可以不需要引入)
//链栈节点
typedef struct Node {
char value;
struct Node* next;
}Node;
//链栈结构体
typedef struct LinkStack {
Node* Front;//栈头
Node* Rear;//栈尾
}LinkStack;
//初始化栈
void InitLinkStack(LinkStack* stack) {
//头节点=尾节点(头节点不附带任何信息)
stack->Front = stack->Rear = (Node*)malloc(sizeof(Node));
}
//栈判空
bool isEmpty(LinkStack* stack) {
return stack->Front == stack->Rear;
}
//加入栈顶
void Push(LinkStack* stack, char c) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->value = c;
newNode->next = stack->Rear;
stack->Rear = newNode;
}
//获取顶部元素
char GetTop(LinkStack* stack) {
return stack->Rear->value;
}
//删除栈顶元素
bool Pop(LinkStack* stack) {
if (isEmpty(stack)){
return false;
}
//临时获取待删除节点
Node* temp = stack->Rear;
stack->Rear = stack->Rear->next;//真正的删除操作
free(temp);//释放空间
return true;
}
//匹配括号。包括小,中,大括号三种
bool match_bracket(char str[], int len) {
LinkStack stack;
InitLinkStack(&stack);
for (int i = 0; i < len; ++i) {
if (str[i] == '(' || str[i] == '[' || str[i] == '{') {
Push(&stack, str[i]);
}
else if (str[i] == ')') {
//如果不为空又是右括号直接判断失败
if (isEmpty(&stack)||GetTop(&stack)!='(') {
return false;
}
//消除左括号
else {
Pop(&stack);
}
}
else if (str[i] == ']') {
if (isEmpty(&stack) || GetTop(&stack) != '[') {
return false;
}
else {
Pop(&stack);
}
}
else if (str[i] == '}') {
if (isEmpty(&stack) || GetTop(&stack) != '{') {
return false;
}
else {
Pop(&stack);
}
}
}
return isEmpty(&stack);//如果匹配完了但是栈不为空说明匹配失败
}
int main() {
char str[1000];
while (1) {
scanf_s("%s", str, sizeof(str));
if (match_bracket(str, strlen(str))) {
printf("匹配成功!\n");
}
else {
printf("匹配失败!\n");
}
}
}