#include <iostream>
//#include <cstdlib>
#include <stdlib.h>
class Node {
private:
int data;
Node *left, *right;
public:
static Node *push(Node *root, int data) {
Node *p;
if (!root) {
p = new Node();
p->data = data;
p->left = p->right = 0;
return p;
}
if (data < root->data) {
root->left = push(root->left, data);
return root;
} else {
root->right = push(root->right, data);
return root;
}
}
static Node *pop(Node *root, int &data) {
Node *p;
if (root == 0)
return 0;
if (root->left) {
root->left = pop(root->left, data);
return root;
}
p = root->right;
data = root->data;
delete root;
return p;
}
};
class BinTree {
private:
Node *root;
bool flag;
public:
BinTree() {
root = 0;
flag = false;
}
void pushNode(int data) {
root = Node::push(root, data);
flag = true;
}
bool popNode(int &data) {
root = Node::pop(root, data);
if (!root) {
if (flag) {
flag = false;
return true;
} else
return false;
} else
return true;
}
};
int main() {
const int n = 10;
const int max = 1000;
const int seed = 31415926;
int data;
BinTree *obj = new BinTree();
srand(seed);
for (int i = 0; i < n; i++) {
data = rand() % max;
obj->pushNode(data);
}
std::cout << "C++(1)" << std::endl;
while (obj->popNode(data))
std::cout << data << std::endl;
delete obj;
return 0;
}
/* end */
I2luY2x1ZGUgPGlvc3RyZWFtPgovLyNpbmNsdWRlIDxjc3RkbGliPgojaW5jbHVkZSA8c3RkbGliLmg+CgpjbGFzcyBOb2RlIHsKcHJpdmF0ZToKICBpbnQgZGF0YTsKICBOb2RlICpsZWZ0LCAqcmlnaHQ7CnB1YmxpYzoKICBzdGF0aWMgTm9kZSAqcHVzaChOb2RlICpyb290LCBpbnQgZGF0YSkgewogICAgTm9kZSAqcDsKICAgIGlmICghcm9vdCkgewogICAgICBwID0gbmV3IE5vZGUoKTsKICAgICAgcC0+ZGF0YSA9IGRhdGE7CiAgICAgIHAtPmxlZnQgPSBwLT5yaWdodCA9IDA7CiAgICAgIHJldHVybiBwOwogICAgfSAKICAgIGlmIChkYXRhIDwgcm9vdC0+ZGF0YSkgewogICAgICByb290LT5sZWZ0ID0gcHVzaChyb290LT5sZWZ0LCBkYXRhKTsKICAgICAgcmV0dXJuIHJvb3Q7CiAgICB9IGVsc2UgewogICAgICByb290LT5yaWdodCA9IHB1c2gocm9vdC0+cmlnaHQsIGRhdGEpOwogICAgICByZXR1cm4gcm9vdDsKICAgIH0KICB9CiAgc3RhdGljIE5vZGUgKnBvcChOb2RlICpyb290LCBpbnQgJmRhdGEpIHsKICAgIE5vZGUgKnA7CiAgICBpZiAocm9vdCA9PSAwKQogICAgICByZXR1cm4gMDsKICAgIGlmIChyb290LT5sZWZ0KSB7CiAgICAgIHJvb3QtPmxlZnQgPSBwb3Aocm9vdC0+bGVmdCwgZGF0YSk7CiAgICAgIHJldHVybiByb290OwogICAgfQogICAgcCA9IHJvb3QtPnJpZ2h0OwogICAgZGF0YSA9IHJvb3QtPmRhdGE7CiAgICBkZWxldGUgcm9vdDsKICAgIHJldHVybiBwOwogIH0KfTsKCmNsYXNzIEJpblRyZWUgewpwcml2YXRlOgogIE5vZGUgKnJvb3Q7CiAgYm9vbCBmbGFnOwpwdWJsaWM6CiAgQmluVHJlZSgpIHsKICAgIHJvb3QgPSAwOwogICAgZmxhZyA9IGZhbHNlOwogIH0KICB2b2lkIHB1c2hOb2RlKGludCBkYXRhKSB7CiAgICByb290ID0gTm9kZTo6cHVzaChyb290LCBkYXRhKTsKICAgIGZsYWcgPSB0cnVlOwogIH0KICBib29sIHBvcE5vZGUoaW50ICZkYXRhKSB7CiAgICByb290ID0gTm9kZTo6cG9wKHJvb3QsIGRhdGEpOwogICAgaWYgKCFyb290KSB7CiAgICAgIGlmIChmbGFnKSB7CiAgICAgICAgZmxhZyA9IGZhbHNlOwogICAgICAgIHJldHVybiB0cnVlOwogICAgICB9IGVsc2UKICAgICAgICByZXR1cm4gZmFsc2U7CiAgICB9IGVsc2UKICAgICAgcmV0dXJuIHRydWU7CiAgfQp9OwoKaW50IG1haW4oKSB7CiAgY29uc3QgaW50IG4gPSAxMDsKICBjb25zdCBpbnQgbWF4ID0gMTAwMDsKICBjb25zdCBpbnQgc2VlZCA9IDMxN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