#include <iostream>
#include <vector>
#include <climits>
#define swap(a, b) {int tmp=a; a=b; b=tmp;}
using namespace std;

//힙정렬 유지
void heapify(vector<int> &v, int root) {
	int left = root*2 + 1, right= root*2 + 2;

	if (left < v.size() && v[root] > v[left]) {
		swap(v[root], v[left]);
		heapify(v, left);
	}
	if (right < v.size() && v[root] > v[right]) {
		swap(v[root], v[right]);
		heapify(v, right);
	}
}

void print(vector<int>& v) {
	if (v.empty()) {
		cout << 0 << "\n";
		return;
	}

	cout << v.front() << "\n";
	swap(v[0], v[v.size() - 1]);
	v.pop_back();
	heapify(v, 0);
}

int main() {
	cin.tie(NULL);
	int n, var=0;
	cin >> n;
	vector<int> v;

	for (int i = 0; i < n; i++) {
		cin >> var;
		if (var) {
			v.insert(v.begin(), var);
			heapify(v, 0);
		}
		else {
			print(v);
		}
	}

	return 0;
}