create stackApp, which includes convertion of number system, and parenthesis matching.

This commit is contained in:
Shine wOng
2019-05-20 12:41:08 +08:00
parent 6c596c93d4
commit b8b04e8627
4 changed files with 113 additions and 1 deletions

55
thu_dsa/chp4/stackApp.cpp Normal file
View File

@@ -0,0 +1,55 @@
#include "../chp2/Fib.h"
#include "stackApp.h"
/*
* @brief : convert a decimal digit n to any base(2 <= base <= 36)
* @args :
* @return: return the result in the form of char*
*/
char* convert(__int64 n, int base){
Stack<char> charStack;
while(n != 0){
charStack.push(digits[n % base]);
n /= base;
}
char* res = new char[charStack.getSize() + 1];
int pos = 0;
while (!charStack.empty()) res[pos++] = charStack.pop();
res[pos] = '\0';
return res;
}
/*
* @brief : to judge if an expression of matches
* @args : exp
* @return: return true if matches
*/
bool paren(const char exp[]){
Stack<char> parenStack;
char currParen, popped;
for(int ix = 0; (currParen = exp[ix]) != '\0'; ++ix){
switch(currParen){
case '(':
case '[':
case '{':
parenStack.push(currParen);
break;
case ')':
if (parenStack.empty()) return false;
if (parenStack.pop() != '(') return false;
break;
case ']':
if (parenStack.empty()) return false;
if (parenStack.pop() != '[') return false;
break;
case '}':
if (parenStack.empty()) return false;
if (parenStack.pop() != '{') return false;
break;
}
}
return parenStack.empty()? true : false;
}

24
thu_dsa/chp4/stackApp.h Normal file
View File

@@ -0,0 +1,24 @@
#ifndef STACKAPP_H_
#define STACKAPP_H_
#include "Stack.h"
static char digits[] = { '0','1','2','3','4','5','6','7','8','9',
'a','b','c','d','e','f','g','h','i','j',
'k','l','m','n','o','p','q','r','s','t',
'u','v','w','x','y','z' };
/*
* @brief : convert a decimal digit n to any base(2 <= base <= 36)
* @args :
* @return: return the result in the form of char*
*/
char* convert(__int64 n, int base);
/*
* @brief : to judge if an expression of parens matches
* @args : exp
* @return: return true if matches
*/
bool paren(const char exp[]);
#endif

View File

@@ -9,7 +9,7 @@
void test_basic();
void test_capacity();
int main(){
int stack_test_main(){
test_basic();
test_capacity();

View File

@@ -0,0 +1,33 @@
#include "../chp2/Fib.h"
#include "stackApp.h"
#include <iostream>
#include <cassert>
using std::cout;
using std::endl;
void test_convert();
void test_paren();
int main(){
cout << "Running tests......" << endl;
test_convert();
test_paren();
cout << "All tests passed." << endl;
system("pause");
return 0;
}
void test_convert(){
assert(strcmp(convert(1314, 16), "522") == 0);
assert(strcmp(convert(520, 2), "1000001000") == 0);
assert(strcmp(convert(520, 16), "208") == 0);
}
void test_paren(){
assert(paren("(())") == true);
assert(paren("()()") == true);
assert(paren("[(])") == false);
assert(paren("{[()]{[({})]}}") == true);
}