利用栈进行程序的括号匹配
程序代码:
/*
* fanchen.cpp : 定义控制台应用程序的入口点。
*
*/
#include "stdafx.h"
#include <iostream>
using namespace std;
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
const int Arsize = 60;
class MyStack {
public:
/* 判断栈是否是空 */
bool isEmpty()
{
if ( number == 0 )
{
return(true);
}else{
return(false);
}
}
/* 入栈操作 */
bool push( char c )
{
if ( number >= maxNumber )
{
return(false);
}
number++;
array[number] = c;
}
/* 出栈操作 */
char pop()
{
if ( isEmpty() )
{
return(-1);
}
return(array[number--]);
}
MyStack()
{
number = 0;
}
private:
/* 栈内的数据数量 */
int number;
static int maxNumber;
char array[100];
};
int MyStack::maxNumber = 100;
/**
此处注意传递的参数,如不用取地址符,则在此函数内会新建一个对象
*/
bool check( MyStack &stack, char c )
{
char temp;
switch ( c )
{
case '[':
case '{':
case '(':
case '<':
stack.push( c );
break;
case ']':
temp = stack.pop();
cout << "出栈:" << c << " " << temp << endl;
if ( temp != '[' )
{
return(false);
}
break;
case '}':
temp = stack.pop();
cout << "出栈:" << c << " " << temp << endl;
if ( temp != '{' )
{
return(false);
}
break;
case ')':
temp = stack.pop();
cout << "出栈:" << c << " " << temp << endl;
if ( temp != '(' )
{
return(false);
}
break;
case '>':
temp = stack.pop();
cout << "出栈:" << c << " " << temp << endl;
if ( temp != '<' )
{
return(false);
}
break;
}
return(true);
}
int main()
{
/* 自定义栈类 */
MyStack stack;
/* 暂存字符 */
char c;
/* 存储数组 */
char fileName[Arsize];
cout << "Please enter the file's name:\n";
/* 读取文件path */
cin.getline( fileName, Arsize );
/* 定义文件读写流 */
fstream inFile;
/* 打开文件 */
inFile.open( fileName );
if ( !inFile.is_open() )
{
cout << "Could not find the file\n";
cout << "Program terminating\n";
exit( EXIT_FAILURE );
}
/* 读取字符并赋值给c */
inFile >> c;
/* 文件没有结束 */
bool flag = true;
while ( !inFile.eof() )
{
if ( inFile.good() )
{
if ( !check( stack, c ) )
{
cout << "匹配失败!" << endl;
flag = false;
break;
}
inFile >> c;
}
}
if ( flag )
{
cout << "括号完全匹配" << endl;
}
system( "pause" );
return(0);
}
测试文件:
H.js
var http = require('http');
var querystring = require('querystring');
var postHTML =
'<html><head><meta charset="utf-8"><title>菜鸟教程 Node.js 实例</title></head>' +
'<body>' +
'<form method="post">' +
'网站名: <input name="name"><br>' +
'网站 URL: <input name="url"><br>' +
'<input type="submit">' +
'</form>' +
'</body></html>';
http.createServer(function (req, res) {
var body = "";
req.on('data', function (chunk) {
body += chunk;
});
req.on('end', function () {
// 解析参数
body = querystring.parse(body);
// 设置响应头部信息及编码
res.writeHead(200, {'Content-Type': 'text/html; charset=utf8'});
if(body.name && body.url) { // 输出提交的数据
res.write("网站名:" + body.name);
res.write("<br>");
res.write("网站 URL:" + body.url);
} else { // 输出表单
res.write(postHTML);
}
res.end();
});
}).listen(3000);