用栈解决括号匹配问题

#define _CRT_SECURE_NO_WARNINGS 1

#include <stdio.h>

#include <stdlib.h>

#include <assert.h>

typedef char DataType;

#define _capacity 100// 底层空间的总大小

typedef struct Stack

{

DataType _array[_capacity];

int _top; // 表示有效元素个数 表示栈顶位置  

}Stack;

//初始化

void StackInit(Stack* s)

{

s->_top = 0;

}

// 入栈 

void StackPush(Stack* s, DataType data)

{

if (s->_top ==_capacity )

{

printf(“栈满!!!”);

}

s->_array[s->_top++] = data;

}

// 出栈 

void StackPop(Stack* s)

{

if (s->_top == 0)

{

printf(“栈为空!!!”);

return;

}

s->_top–;

}

// 获取栈顶元素 

DataType StackTop(Stack* s)

{

if (s->_top == 0)

{

printf(“栈为空!!!”);

return 0;

}

DataType x = s->_array[s->_top-1];

return x;

}

// 有效元素的个数 

int StackSize(Stack* s)

{

return s->_top;

}

// 检测栈是否为空 

int StackEmpty(Stack* s)

{

if (s->_top == 0)

return 1;

return 0;

}

//打印

void printstack(Stack * s)

{

if (s->_top == 0)

{

printf(“栈为空!!!”);

}

while (s->_top)

{

printf(“%d “, s->_array[–s->_top]);

}

}

// 栈的应用 

//2. 用栈解决括号匹配问题,测试用例见课件、

int lookupbracket(Stack *s, char *str)

{

//          { [ ( ) ] }

while (*str != ‘\0’)

{

char c = *str;

switch (c)

{

case ‘(‘:

{    

StackPush(s, c);

           break;

}

case ‘{‘:

{

StackPush(s, c);

break;

}

case ‘[‘:

{

StackPush(s, c);

break;

}

case ‘)’:

{

if (StackTop(s) == ‘(‘)

{

StackPop(s);

}

break;

}

case ‘}’:

{

if (StackTop(s) == ‘{‘)

{

StackPop(s);

}

break;

}

case ‘]’:

{

if (StackTop(s) == ‘[‘)

{

StackPop(s);

}

break;

}

}

str++;

}

return s->_top;

}

//3. 用栈求解后缀表达式值

int suffix_expression(Stack *s, char *str)

{

//       15\4\5\*\+

assert(str);

int tmp1 = 0;

int tmp2 = 0;

int num = 0;

while (*str != ‘\0’)

{

char c = *str;

if (c >= ‘0’&&c <= ‘9’)

{

StackPush(s,c – ‘0’);

}

else if (c == ‘+’)

{

tmp1=StackTop(s);

StackPop(s);

tmp2 = StackTop(s);

StackPop(s);

num = tmp1+tmp2;

StackPush(s, num);

}

else if (c == ‘-‘)

{

tmp1 = StackTop(s);

StackPop(s);

tmp2 = StackTop(s);

StackPop(s);

num = tmp1-tmp2;

StackPush(s, num);

}

else if (c == ‘*’)

{

tmp1 = StackTop(s);

StackPop(s);

tmp2 = StackTop(s);

StackPop(s);

num = tmp1*tmp2;

StackPush(s, num);

}

else if (c == ‘/’)

{

tmp1 = StackTop(s);

StackPop(s);

tmp2 = StackTop(s);

StackPop(s);

num = tmp1/tmp2;

StackPush(s, num);

}

str++;

}

return StackTop(s);

}

int main()

{

Stack s;

char str[7] = “15\4\5\*\+”;

StackInit(&s);

printf(“%d”, suffix_expression(&s, str));

system(“pause”);

return 0;

}

    原文作者:括号匹配问题
    原文地址: https://blog.csdn.net/champion_man/article/details/80010334
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞