不相交集合的链表实现

// disjoint_set.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#define noFind -1
using namespace std;

typedef struct node *Position;
typedef struct node *Head;
//链表节点,对于头节点,key存放的的是链表的长度,普通节点则是数据
//对于头结点,tail存放的是链表末尾的地址,普通节点的tail相当于Next
//对于头结点,head存放的是链表第一个元素的位置,也就是代表,普通节点的head则指向表头。
struct node
{
	Position head;
	Position tail;
	int key;
};

//建立一个只有一个元素的新集合//////////////////////
Head make_set(int x)
{
	Head head = (Head)malloc(sizeof(node));
	head->key = 1;

	Position p = (Position)malloc(sizeof(node));
	p->key = x;
	p->head = head;
	p->tail = NULL;

	head->head = head->tail = p;
	return head;
}

/*/从集合的数组中找到x所属于的集合 (错误版本)////////////////////
int Find_set(Head *head_of_Head, int n, int x)
{
	Position p;
	for (int i = 0; i < n; i++)
	{
		p = head_of_Head[i]->head;
		while (p)
		{
			if (p->key == x)
				return head_of_Head[i]->head->key;
			else
				p = p->tail;
		}
	}
	return noFind;
}
*/////////////////////////////////////////////////////////
// 从集合的数组中找到x所属于的集合(修正版本)////////////////////
int Find_set(Head x)
{
	return (x->head)->head->key;   //返回代表元素
}
//////////////////////////////////////////////////////////////////////////

//合并两个集合/////////////////////////////////
Head Union(Head head1, Head head2)
{
	Head tempHead;
	if (head1->key < head2->key)
	{
		tempHead = head1;
		head1 = head2;
		head2 = tempHead;
	}

	head1->tail->tail = head2->head;
	Position p = head2->head;
	while (p)
	{
		p->head = head1;
		p = p->tail;
	}
	head1->key += head2->key;
	return head1;
}

//打印集合/////////////////////////////////
void print(Head head)
{
	Position p = head->head;
	while (p)
	{
		cout << p->key << '	';
		p = p->tail;
	}
	cout << endl;
}

int main()
{
	Head head1 = make_set(1);
	cout << Find_set(head1->head) << endl;;
	Head head2 = make_set(2);
	Head head3 = make_set(3);
	print(head1);
	print(head2);
	print(Union(head1, head2));
	cout << Find_set(head2->head) << endl;;
	print(head3);
	head1 = Union(head3, head2);
	print(head1);

	cout << Find_set(head3->head) << endl;;
    
	while (1);
    return 0;
}

  

原文地址:https://www.cnblogs.com/linear/p/6724330.html