【栈】用栈实现等价类划分问题

书上的例子实在晦涩难懂,写了好久,代码能运行,但是待改进

#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;


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值