C,
pasted
on Apr 14:
|
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
struct node {
int n;
struct node *left;
struct node *right;
};
void push(struct node **root, int n) {
struct node *p;
if (!*root) {
p = malloc(sizeof(struct node));
p->n = n;
p->left = p->right = NULL;
*root = p;
return;
}
if (n != (*root)->n) {
if (n < (*root)->n) {
push(&((*root)->left), n);
} else {
push(&((*root)->right), n);
}
}
}
int pop(struct node **root) {
struct node *p;
int n;
if (*root == NULL)
return -1;
if ((*root)->left)
return pop(&((*root)->left));
assert((*root)->left == NULL);
p = *root;
n = p->n;
*root = p->right;
free(p);
return n;
}
#define N 9
int main() {
int i, n, a, b, c;
struct node *root = NULL;
push(&root, 1);
for (i = 0; i < N; i++) {
n = pop(&root);
a = 2 * n + 1; b = 3 * n + 1; c = 5 * n + 1;
printf("%d: %d, %d, %d\n", n, a, b, c);
push(&root, a);
push(&root, b);
push(&root, c);
}
while (pop(&root) > 0)
;
return 0;
}
/* end */
|
Output:
|
1: 3, 4, 6
3: 7, 10, 16
4: 9, 13, 21
6: 13, 19, 31
7: 15, 22, 36
9: 19, 28, 46
10: 21, 31, 51
13: 27, 40, 66
15: 31, 46, 76
|
|