//.h文件
#ifndef STACK_H_
#define STACK_H_
typedef char itemType;
class Stack
{
public:
Stack();
~Stack();
Stack(const Stack & aStack);
bool isempty();
void push(itemType newItem);
void pop();
void pop(itemType & stackTop);
itemType getTop();
private:
typedef struct Node
{
itemType item;
Node * next;
}LinkList,*pLinkList;
pLinkList topPtr;
};
#endif
//.h文件
#ifndef EXCEPTION_H_
#define EXCEPTION_H_
#include<exception>
#include<string>
using namespace std;
class StackException:public exception
{
public:
StackException(const string&message=" ")
:exception(message.c_str()) {}
};
#endif
//.cpp文件
#include"1.h"
#include"6.h"
#include<cstdlib>
#include<iostream>
using namespace std;
Stack::Stack():topPtr(NULL) {}
Stack::Stack(const Stack & aStack)
{
topPtr=new LinkList;
topPtr->item=aStack.topPtr->item;
pLinkList newPtr=topPtr;
for(pLinkList origPtr=aStack.topPtr->next;origPtr!=NULL;origPtr=origPtr->next)
{
newPtr->next=new LinkList;
newPtr=newPtr->next;
newPtr->item=origPtr->item;
}
}
bool Stack::isempty()
{
return topPtr==NULL;
}
void Stack::push(itemType newItem)
{
pLinkList newPtr=new LinkList;
newPtr->item=newItem;
newPtr->next=topPtr;
topPtr=newPtr;
}
void Stack::pop()
{
pLinkList temp=topPtr;
topPtr=topPtr->next;
temp->next=NULL;
delete temp;
}
void Stack::pop(itemType & stackTop)
{
stackTop=topPtr->item;
pLinkList temp;
temp=topPtr;
topPtr=topPtr->next;
temp->next=NULL;
delete temp;
}
itemType Stack::getTop()
{
if(isempty())
throw StackException("ERROR!!!");
return topPtr->item;
}
Stack::~Stack()
{
pLinkList temp;
while(topPtr!=NULL)
{
temp=topPtr;
topPtr=topPtr->next;
delete temp;
}
}
//main函数
#include"1.h"#include<iostream>
#include<string>
int precedence(char ch)
{
switch(ch)
{
case '+':
return 1;
break;
case '-':
return 1;
break;
case '*':
return 2;
break;
case '/':
return 2;
break;
default:
return 0;
break;
}
}
int main()
{
using namespace std;
using std::string;
Stack aStack;
string str;
string postfixExp;
cout<<"Enter str pleace: ";
cin>>str;
for(int i=0;i<str.size();++i)
{
switch(str[i])
{
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
postfixExp=postfixExp+str[i];
break;
case '(':
aStack.push(str[i]);
break;
case ')':
while(aStack.getTop()!='(')
{
postfixExp=postfixExp+aStack.getTop();
aStack.pop();
}
aStack.pop();
break;
case '+':
case '-':
case '*':
case '/':
while((!aStack.isempty())&&(aStack.getTop()!='(')&&(precedence(str[i])<=precedence(aStack.getTop())))
{
postfixExp=postfixExp+aStack.getTop();
aStack.pop();
}
aStack.push(str[i]);
break;
}
}
while(!aStack.isempty())
{
postfixExp=postfixExp+aStack.getTop();
aStack.pop();
}
cout<<postfixExp<<endl;
return 0;
}