写在前面
这些代码是我的数据结构作业,发出来一方面同大家分享,另一方面跪求大佬指出代码需要改进的地方。
#include<iostream>//基于栈的括号匹配
#include<fstream>
using namespace std;
typedef char TYPE;//抽象数据类型
typedef struct node {
TYPE data;
struct node* next;
}node, *link;
link creat() {
link head;
head = (link)malloc(sizeof(node));
head->data=-1;
head->next = NULL;
return head;
}//生成链表
void push(link str, TYPE op) {//压栈
link temp;
temp = (link)malloc(sizeof(node));
temp->data = op;
temp->next = str->next;
str->next = temp;
}
void pop(link str) {//弹栈
link temp;
temp = str->next;
str->next = temp->next;
free(temp);
}
int main() {
link a;
a = creat();
TYPE temp[10000];
ifstream inf("string.txt", ios::in);//放在cpp文件所在的文件夹中
ofstream outf("values.txt", ios::out);
inf.getline(temp, 1000);
int i = 0; //预先读取一行字符串进行判断
while ( !inf.eof() ) {
while(temp[i] !='\0' && !inf.eof()){//数据行内进行判断
if(temp[i] =='{'|| temp[i] =='['|| temp[i] =='('){//逐位读遇到左括号就压栈
push(a, temp[i]);
}
switch(temp[i]){//判断括号是否符合及弹栈操作
case '}':
if (a->next != NULL) {//未到栈底
if (a->next->data == '{') {
pop(a);
}
else {//符号不匹配
outf << -1 << endl;
inf.getline(temp, 10000);//读文件下一行 继续进行对比操作
a = creat();
i = -1;
}
}
else{//已经到栈底
outf << -1 << endl;
inf.getline(temp, 10000);
a = creat();
i = -1;
}
break;
case ']':
if (a->next != NULL) {
if (a->next->data == '[') {
pop(a);
}
else {
outf << -1 << endl;
inf.getline(temp, 10000);
a = creat();
i = -1;
}
}
else {
outf << -1 << endl;
inf.getline(temp, 10000);
a = creat();
i = -1;
}
break;
case ')':
if (a->next != NULL) {
if (a->next->data == '(') {
pop(a);
}
else {
outf << -1 << endl;
inf.getline(temp, 10000);
a = creat();
i = -1;
}
}
else {
outf << -1 << endl;
inf.getline(temp, 10000);
a = creat();
i = -1;
}
break;
}
i++;
}
if (a->next==NULL) {//成功比较完一整行字符 看栈是否为空栈
outf << 0 << endl;
}
else {
outf << -1 << endl;
}
inf.getline(temp, 10000);
a = creat();
i = 0;
}
inf.close();
outf.close();
return 0;
}
代码如上