c語言——棧的應用(應近匹配)
幾乎所有的編譯器都具有檢測括號是否匹配的能力那麼如何實現編譯器中的符號成對
檢測如下字符串
5+5*(6)+9/3*1)-(1+3(
路算法思
從第一個字符開始掃描
當遇見普通字符時忽略
當遇見左符號時壓入棧中
當遇見右符號時從棧中彈出棧頂符號,並進行匹配
匹配成功:繼續讀入下一個字符
匹配失敗:立即停止,並報錯
結束
成功:所有字符掃描完畢,且棧爲空
代碼
頭文件SeqStack.h
#pragma once
#include<stdlib.h>
#include<string.h>
#ifdef __cplusplus
extern "C"{
#endif
#define MAX 1024
//順序棧數據結構
struct SStack
{
void *data[MAX]; //存放數據的數組
int size;//棧中元素的個數
};
typedef void * SeqStack;
//數組高下標的位置當做棧頂,因爲不需要移動數組中的元素在插入和刪除中
//初始化
SeqStack Init_SeqStack();
//入棧
void Push_SeqStack(SeqStack stack, void *data);
//出棧
void Pop_SeqStack(SeqStack stack);
//獲得棧頂元素
void *Top_SeqStack(SeqStack stack);
//獲得棧的大小
int Size_SeqStack(SeqStack stack);
//銷燬棧
void Destroy_SeqStack(SeqStack stack);
#ifdef __cplusplus
}
#endif
SeqStack.c
#include"SeqStack.h"
//初始化
SeqStack Init_SeqStack()
{
struct SStack *stack = malloc(sizeof(struct SStack));
if (NULL == stack)
{
return NULL;
}
//memset(stack->data, 0, sizeof(struct SStack));
stack->size = 0;
for (int i = 0; i < MAX; ++i)
{
stack->data[i] = NULL;
}
return stack;
}
//入棧
void Push_SeqStack(SeqStack stack, void *data)
{
if (NULL == stack)
{
return;
}
if (NULL == data)
{
return;
}
struct SStack *s = (struct SStack *)stack;
if (s->size == MAX)
{
return;
}
s->data[s->size] = data;
s->size++;
}
//出棧
void Pop_SeqStack(SeqStack stack)
{
if (NULL == stack)
{
return;
}
struct SStack *s = (struct SStack *)stack;
if (s->size == 0)
{
return;
}
s->data[s->size - 1] = NULL;
s->size--;
}
//獲得棧頂元素
void *Top_SeqStack(SeqStack stack)
{
if (NULL == stack)
{
return NULL;
}
struct SStack *s = (struct SStack *)stack;
if (s->size == 0)
{
return NULL;
}
return s->data[s->size - 1];
}
//獲得棧的大小
int Size_SeqStack(SeqStack stack)
{
if (NULL == stack)
{
return -1;
}
struct SStack *s = (struct SStack *)stack;
return s->size;
}
//銷燬棧
void Destroy_SeqStack(SeqStack stack)
{
if (NULL == stack)
{
return;
}
free(stack);
}
棧的應用_就近匹配
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include"SeqStack.h"
int IsLeft(char ch)
{
return ch == '(';
}
int IsRight(char ch)
{
return ch == ')';
}
void printError(const char *str,char *errMsg,char *pos)
{
printf("錯誤信息:%s\n", errMsg);
printf("%s\n",str);
int dis = pos - str;
for (int i = 0; i < dis; ++i)
{
printf(" ");
}
printf("A\n");
}
void test()
{
const char *str = "5+5*(6()+9/3*1)-(1)+3(";
char *p = (char *)str;
//初始化棧
SeqStack stack = Init_SeqStack();
while (*p != '\0')
{
//判斷當前字符是否是左括號
if (IsLeft(*p))
{
Push_SeqStack(stack, p);
}
//判斷當前字符是否是右括號
if (IsRight(*p))
{
if (Size_SeqStack(stack) > 0)
{
//彈出棧頂元素
Pop_SeqStack(stack);
}
else
{
printError(str,"右括號沒有匹配的左括號!",p);
}
}
p++;
}
while (Size_SeqStack(stack) > 0)
{
printError(str,"沒有匹配的右括號!",Top_SeqStack(stack));
//彈出棧頂元素
Pop_SeqStack(stack);
}
//銷燬棧
Destroy_SeqStack(stack);
stack = NULL;
}
int main(){
test();
system("pause");
return EXIT_SUCCESS;
}
運行
錯誤信息:沒有匹配的右括號!
5+5*(6()+9/3*1)-(1)+3(
A