书上的例子实在晦涩难懂,写了好久,代码能运行,但是待改进
#include <iostream>
using namespace std;
class stack
{
public:
int num;
stack* next;
stack()
{
next = NULL;
}
};
class op_stack
{
public:
int top;
int out[50];
int arr[50];
stack* my_stack[50];
int stack_arr[100];
op_stack()
{
for (int i = 0; i < 50; i++)
{
out[i] = 0;
}
for (int i = 0; i < 50; i++)
{
my_stack[i] = NULL;
}
this->top = -1;
}
void init_stack(int number) //初始化,建立number个链表
{
for (int i = 0; i < number; i++)
{
my_stack[i] = new stack;
my_stack[i]->next = NULL;
my_stack[i]->num = i + 1;
}
}
void link(int number) //输入number组的等价类,建立联系
{
cout << "请输入" << number << "组等价类" << endl;
for (int i = 0; i < number; i++)
{
cout << "请输入第" << i << "组等价类" << endl;
int a, b;
cin >> a >> b;
//接下来就是互相存储等价类了
add(my_stack[a - 1], b);
add(my_stack[b - 1], a);
}
}
void add(stack* my_stack,int temp)
{
stack* ptr1=NULL, * ptr2=NULL;
ptr1 = my_stack;
while (ptr1)
{
ptr2 = ptr1;
ptr1 = ptr1->next;
}
ptr1 = new stack;
ptr1->num = temp;
ptr2->next = ptr1;
ptr1->next = NULL;
}
void list_add()
{
cout << "请问有几组等价关系呢?" << endl;
int temp;
cin >> temp;
for (int i = 0; i < temp; i++)
{
cout << "请输入两个等价关系" << endl;
int temp1, temp2;
cin >> temp1 >> temp2;
add(my_stack[temp1-1], temp2);
}
}
void push_same(stack* my_stack)
{
stack* ptr = my_stack;
while (ptr)
{
if (out[(ptr->num) -1] == 0)
{
top++;
stack_arr[top] = ptr->num;
arr[ptr->num] = 1;
out[ptr->num -1] = 1;
}
ptr = ptr->next;
}
}
int pop()
{
if (this->top == -1)
{
return 0;
}
return stack_arr[top-- ];
}
void print(int number)
{
for (int i = 0; i < number; i++)
{
for (int j = 0; j < 50; j++)
{
arr[j] = 0;
}
this->top = -1;
push_same(my_stack[i]);
while (this->top != -1)
{
int temp = pop();
temp--;
push_same(my_stack[temp]);
}
int flag = 0;
for (int k = 0; k <= 50; k++)
{
if (arr[k] == 1)
{
cout << k << " ";
flag = 1;
}
if (flag == 1 && k == 50)
{
cout << endl;
}
}
}
}
};
int main()
{
op_stack my_op_stack;
cout << "请问一共有几个数据呢" << endl;
int number;
cin >> number;
my_op_stack.init_stack(number);
my_op_stack.list_add();
cout << "等价类关系如下所示" << endl;
my_op_stack.print(number);
return 0;
}