#include<iostream>
#include<fstream>
using namespace std;
struct Node;
typedef struct Node* PtrToNode;
typedef PtrToNode Stack;
typedef PtrToNode Position;
//创建栈节点
struct Node
{
char element;//节点数据域
PtrToNode next;//指针域
};
//判断栈是否为空
int IsEmpty(Stack S)
{
return S->next == NULL;
}
//弹出数据
char Pop(Stack S)
{
char X;
PtrToNode FirstCell;
if (IsEmpty(S)) return -1;
else
{
FirstCell = S->next;//将头结点赋值给暂时存储位置
S->next = S->next->next;
X = FirstCell->element;//弹出的数据
free(FirstCell);//free掉第一个即最后一个输入的数据
cout << "弹出" << X << endl;
return 0;
}
cout << endl;
}
//置空数据
int MakeEmpty(Stack S)
{
if (S == NULL) return -1;
else
while (!IsEmpty(S))
Pop(S);
return 0;
}
//创建栈
Stack CreateStack()
{
Stack S = (PtrToNode)malloc(sizeof(struct Node));
if (S == NULL)
{
cout << "分配内存失败!" << endl;
return S;
}
else
S->next = NULL;
return S;
}
//将数据输入到栈中
int Push(char X, Stack S)
{
PtrToNode TmpCell;
TmpCell = (PtrToNode)malloc(sizeof(struct Node));
if (TmpCell == NULL) return -1;
else {
TmpCell->element = X;
TmpCell->next = S->next;
S->next = TmpCell;
return 0;
}
}
//返回栈顶
char Top(Stack S)
{
char x;
if (!IsEmpty(S)) {
x = S->next->element;
return x;
}
return -1;
}
//输出栈中的内容
void Show(Stack& S)
{
Position p = S->next;
if (p == NULL)
cout << "栈已空!" << endl;
else
{
while (p != NULL)
{
cout << p->element << " ";
p = p->next;
}
}
cout << endl;
}
int main()
{
Stack S;
S = CreateStack();
//将算术式输入到文件中,便于后面提取
ofstream output;
output.open("cha.txt");
char cha[100];
cout << "请输入算术式:";
cin >> cha;
output << cha;
output.close();
ifstream input;
input.open("cha.txt");
char tmp;//用于存储读进来的字符
input >> tmp;
while (!input.eof())
{
if (tmp == '(' || tmp == '[' || tmp == '{')
{
Push(tmp, S);
}
if (tmp == ')')
{
if (Top(S) == '(' && (!IsEmpty(S)))
Pop(S);
else
cout << "1Wrong!" << endl;
}
if (tmp == ']')
{
if (Top(S) == '[' )
Pop(S);
else
cout << "2Wrong!" << endl;
}
if (tmp == '}')
{
if (Top(S) == '{'&&(!IsEmpty(S)))
Pop(S);
else
cout << "3Wrong!" << endl;
}
input >> tmp;
}
if (!IsEmpty(S))
cout << "4Wrong!" << endl;
input.close();
return 0;
}
08-23
273