似乎没有把数据存储进去,不知道为什么,请看看
#include<iostream>
using namespace std;
const int MaxVnNum = 20;
const int MaxVtNum = 20;
const int Max = 20;
struct Vt {
int num;
char right[Max];
struct Vt *next;
};
struct Vn {
char vn;
struct Vt vt;
};
struct Vn grammar[MaxVnNum];
//创建表头,即创建结构体变量
struct Vt* createHead()
{
//1.动态内存申请
struct Vt* headNode = (struct Vt*)malloc(sizeof(struct Vt));
//(*headNode).next = NULL;
headNode->next = NULL;//变量要初始化
return headNode; //返回变量
}
struct Vt* createNode(int data,string exper)
{
struct Vt* newNode = (struct Vt*)malloc(sizeof(struct Vt));
newNode->num = data;
for (int m = 0; m < exper.length(); m++)
{
newNode->right[Max] = exper[m];
}
newNode->next = NULL; //作为链表结束标志
return newNode;
}
//表尾插入
void insertByTail(struct Vt* headNode, int data,string exper)
{
struct Vt* newNode = createNode(data,exper);
struct Vt* pTail = headNode;
while (pTail->next != NULL)
{
pTail = pTail->next;
}
pTail->next = newNode;
}
//查找链表
void printList(struct Vt* headNode,char L,int x)
{
//为什么指向第二个节点? 因为第一个节点没有存数据
struct Vt* pMove = headNode->next;
while (pMove->num != x&&pMove->next!=NULL)
{
pMove = pMove->next;
}
if (pMove->next != NULL)
{
cout << L << "->"<<pMove->right ;
}
printf("\n");
}
void enter(int n, Vt* list)
{
//struct Vn grammar[MaxVnNum];
int rcount = 0;
char left;
for (int i = 0; i < n; i++)
{
string exper;
cout << "输入左部:" ;
cin >> left;
grammar[i].vn = left;
cout << "输入右部文法个数:" ;
cin >> rcount;
for (int j = 0; j < rcount; j++)
{
cout << "输入第"<<j+1<<"个表达式:";
cin >> exper;
if (j == 0)
{
createNode(j + 1, exper);
}
else {
insertByTail(list, j + 1, exper);
}
}
}
}
void search(struct Vt* list,char L,int n)
{
int x;
bool a = false;
for (int i = 0; i < n; i++)
{
if (L == grammar[i].vn)
{
cout << "找到对应非终结符" << endl;
cout << "输入查找的第几个式子:";
cin >> x;
printList(list, L, x);
}
}
if (!a)
{
cout << "没有找到对应的产生式";
}
}
int main()
{
struct Vt* list = createHead();
//输入产生式个数
cout << "输入产生式个数"<<endl;
int n;
cin >> n;
//输入产生式,进行存储
enter(n, list);
//输入要寻找的产生式
char w;
cout << "输入要寻找的非终结符的产生式" << endl;
cin >> w;
search(list,w,n);
}