數據結構C++版-棧
阿新 • • 發佈:2018-08-30
current ali cde 就會 類型 color pty tex main
一、概念
二、應用實例
1.進制轉換
#include <stdlib.h>
#include <iostream>
#include <string>
#include "MyStack.h"
#include "Coordinate.h"
using namespace std;
#define BINARY 2
#define OCTONARY 8
#define HEXADECIMAL 16
void main ( )
{
//MyStack<int> s(30);
MyStack<char > s(30);
char num[]="0123456789ABCDEF";
int N=1348;
int mod=0;
while (N!=0)
{
mod=N%16;
s.push(num[mod]);
N=N/16;
}
s.stackTraverse(false);
/*
int elem=0;
for (int i=s.stackLength()-1;i>=0;i--)
{
s.pop(elem);
cout<<num[elem];
} */
/*while(!s.stackEmpty())
{
s.pop(elem);
cout<<num[elem];
}*/
system("pause");
}
2.括號匹配
MyStack<char> s(30); //存放未匹配的括號
MyStack<char> s1(30); //存放棧頂括號的另一半
char str[] = "([])["; //存放待匹配文本目標,要求無空格 e.g. [()()] ([]([]))
char current=0 ; //當前括號需要匹配的另一半
for (int i=0;i<strlen(str);i++)
{
if (current!=str[i])
{
s.push(str[i]);
switch(str[i])
{
case ‘[‘: //case 後面數據類型是int,單個字符會轉換成其ASC碼
if (current!=0)
{
s1.push(current);
}
current=‘]‘;
break;
case ‘(‘:
if (current!=0)
{
s1.push(current);
}
current=‘)‘;
break;
default:
cout<<"括號不匹配."<<endl; //default後面語句可以註釋掉,因為current不等於str[i]時str[i]就會入棧,第一個棧不為零匹配就會失敗
}
}
else
{
char elem;
s.pop(elem);
if(!s1.pop(current))
{
current=0;
}
}
}
if (s.stackEmpty())
{
cout<<"括號匹配"<<endl;
}
else
{
cout<<"括號不匹配"<<endl;
}
system("pause");
數據結構C++版-棧