링크드 리스트 배열 사용
struct node {
int data;
struct node *link;
};
typedef struct node* nodePointer;
short int out[MAX_SIZE];
nodePointer seq[MAX_SIZE];
for(i=0; i<n; i++) {
/* initialize seq and out */
out[i] = TRUE;
seq[i] = NULL;
}
O(n)
/* phase 1: input the equivalence pairs */
printf("Enter a pair of numbers (-1 -1 to quit): ");
scanf("%d%d", &i, &j); /* read a pair of items (i, j) */
while(i >= 0) {
x = (nodePointer)malloc(sizeof(*x)); /* attach node j to item i */
x->data = j;
x->link = seq[i];
seq[i] = x;
x = (nodePointer)malloc(sizeof(*x)); /* attach node i to item j */
x->data = i;
x->link = seq[j];
seq[j] = x;
printf("Enter a pair of numbers (-1 -1 to quit): ");
scanf("%d%d", &i, &j);
}
O(m)
/* phase 2: output the equivalence classes */
// OUT[] : TRUE면 처리해줘야함, FALSE면 이미 처리함
for(i = 0; i < n; i++) {
if(out[i]) {
printf("\\nNew class: %5d", i);
out[i] = FALSE; x = seq[i]; top = NULL;
for( ; ; ) {
while(x) { //when nodes exist in seq[i]
j = x->data;
if(out[j]) {
printf("%5d", j); out[j] = FALSE; //add a node to this class
y = x->link; x->link = top; top = x; //push(node) to stack
x = y; //the next node in seq[i]
}
else x = x->link; //the next node in seq[i]
}
if(!top) break; //if stack EMPTY, search item[i++]
x = seq[top->data]; top = top->link; //else, search item[pop()]
}
}
}
printf("\\n");
O(m + n)
O(m + n)
worst case : m = n(n+1)/2인 경우 O(n^2)