实验内容
实现栈的基本操作:初始化、置栈空、入栈、出栈、取栈顶元素等,并用栈实现括号匹配的检验。
数据结构定义
算法思想及算法设计
括号匹配算法:输入一个由括号组成的字符串,如果是[、{、(三个其中的任何一个,则进栈;若是右括号,则要取此时的栈顶元素,看看是否为与其相对应的左括号,如果是,则讲左括号出栈,如果不是,不进行任何操作。最后通过检验栈是否为空栈,进而判断括号匹配是否成功。
实验代码
头文件
//constant.h
#pragma once
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int Status;
//Stack.h
#pragma once
#include"constant.h"
#define MAXSIZE 100
typedef char Selemtype;
typedef struct
{
int size;
Selemtype* base;
Selemtype* top;
}stack;
Status initstack(stack& s);
Status push(stack& s, Selemtype x);
Status pop(stack& s/*, Selemtype& x*/);
Selemtype gettop(stack& s);
Status clearstack(stack& s);
Status isempty(stack s);
主程序
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include"Stack.h"
#include<string>
using namespace std;
int main()
{
stack s;
initstack(s);
string list;
cin >> list;
for (int i = 0; i < list.length(); i++)
{
switch (list[i])
{
case '(':
case '[':
case '{':
push(s, list[i]);
break;
case ')':
if (gettop(s) == '(')
pop(s);
break;
case ']':
if (gettop(s) == '[')
pop(s);
break;
case '}':
if (gettop(s) == '{')
pop(s);
break;
}
}
if (isempty(s))
cout << "Matched!" << endl;
else
cout << "No matched!"<<endl;
return 0;
}
基本操作函数
#include"Stack.h"
Status initstack(stack& s)
{
s.base = new Selemtype[MAXSIZE];
s.top = s.base;
s.size = MAXSIZE;
return OK;
}
Status push(stack& s, Selemtype x)
{
if (s.top - s.base == s.size)
return ERROR;
*s.top = x;
s.top++;
return OK;
}
Status pop(stack& s/*, Selemtype& x*/)
{
if (s.top == s.base)
return ERROR;
s.top--;
//x = *s.top;
return OK;
}
Selemtype gettop(stack& s)
{
if (s.top != s.base)
return *(s.top - 1);
else
return ERROR;
}
Status clearstack(stack& s)
{
s.top = s.base;
return OK;
}
Status isempty(stack s)
{
if (s.base == s.top)
return OK;
else
return ERROR;
}
分析与总结
算法复杂度:只需从头到尾遍历一次字符串的所有字符即可,所以时间复杂度为O(n)。
优点 | 缺点 |
---|---|
算法思想简单,在数据较少的时候完成判断的速度较快。 | 当输入的数据量较大时,系统会调用很多的堆栈,这样处理相应也会消耗更多时间。 |