本文主要是介绍数据冒险之栈应用(数制转换、括号匹配),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
#include<iostream>
#include"stdlib.h"
#include"MyStack.h"using namespace std;/******************************栈应用----数制转换
描述:输入任意的十进制正整数N,分别输出该整数N的二进制、八进制、十六进制的数公式:N=(N div d)*d+N mod d (div表示整除, mod表示求余)(1348)=(2504)(O)=(544)(0x)=(10101000100)(B)短除法:N N div 8 N mod 81348 168 4168 21 021 2 52 0 2N N div 8 N mod 81348 84 484 5 45 0 5目的:通过实例灵活掌握栈机制的使用技巧
*/
#define BINARY 2
#define OCTONARY 8
#define HEXADECIMAL 16
int main()
{char num[] = "0123456789ABCDE";int elem = 0;MyStack<int> *pStack = new MyStack<int>(40);int N = 0;int mod = 0;int mode = 0;cout << "please input a number :";cin >> N;cout << "Choice a mode from :BINARY,OCTONARY or HEXADECIMAL ";cin >> mode;while (N != 0) //取余{switch (mode){case(2) :mod = N%BINARY;pStack->push(mod);N /= BINARY;break;case(8) :mod = N%OCTONARY;pStack->push(mod);N /= OCTONARY;break;case(16) :mod = N%HEXADECIMAL;pStack->push(mod);N /= HEXADECIMAL;break;default:cout << "sorry,your input is worry" << endl;break;}}// pStack->stackTraverse(0);// for(int i=pStack->stackLength()-1;i>=0;i--)// {// cout<< num[i]// }cout << "the result is : " ;while (!pStack->stackEmpty()){pStack->pop(elem);cout << num[elem];}cout << endl;delete pStack;pStack = NULL;return 0;
}
括号匹配:
#include <iostream>
#include "MyStack.h"
using namespace std;int main(void)
{MyStack<char> *pStack = new MyStack<char>(30); MyStack<char> *pNeedStack = new MyStack<char>(30);/*char *ch;int i, flag = 1;ch = new char[30];cin >> ch;char elem;int length = strlen(ch);for (i = 0; i < length; i++){if (ch[i] == '(' || ch[i] == '['){pStack->push(ch[i]);}else if (ch[i] == ')'){pStack->pop(ch[i]);if (ch[i] != '('){cout << "括号不匹配" << endl;flag = 0;}}else if (ch[i] == ']'){elem = pStack->pop(ch[i]);if (ch[i] != '['){cout << "括号不匹配" << endl;flag = 0;}}}if (pStack->stackLength() != 0){cout << "括号数量不匹配" << endl;flag = 0;}if (flag == 1)cout << "括号匹配" << endl;*/char *str = new char[30];cout << "请输入括号" << endl;cin >> str;char currentNeed = 0;for (int i = 0; i < strlen(str); i++){if (str[i] != currentNeed){pStack->push(str[i]);switch (str[i]){case'[':if (currentNeed != 0){pNeedStack->push(currentNeed);}currentNeed = ']';break;case'(':if (currentNeed != 0){pNeedStack->push(currentNeed);}currentNeed = ')';break;default:cout << "括号不匹配" << endl;return 0;}}else{char elem;pStack->pop(elem);if (!pNeedStack->pop(currentNeed)){currentNeed = 0;}}}if (pStack->stackEmpty()){cout << "括号匹配" << endl;}delete pStack;pStack = NULL;delete pNeedStack;pNeedStack = NULL;return 0;
}
这篇关于数据冒险之栈应用(数制转换、括号匹配)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!