利用栈进行程序的括号匹配
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                利用栈进行程序的括号匹配
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                利用棧進行程序的括號匹配
程序代碼:
/** 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);運行測試:
總結
以上是生活随笔為你收集整理的利用栈进行程序的括号匹配的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: 约瑟夫环问题(带密码)
 - 下一篇: 队列的应用