During the lunch break all n Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working.

Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of the student that stands in line directly in front of him, and the student that stands in line directly behind him. If no one stands before or after a student (that is, he is the first one or the last one), then he writes down number 0 instead (in Berland State University student IDs are numerated from 1).

After that, all the students went about their business. When they returned, they found out that restoring the queue is not such an easy task.

Help the students to restore the state of the queue by the numbers of the student ID's of their neighbors in the queue.


-----Input-----

The first line contains integer n (2 ≤ n ≤ 2·10^5) — the number of students in the queue. 

Then n lines follow, i-th line contains the pair of integers a_{i}, b_{i} (0 ≤ a_{i}, b_{i} ≤ 10^6), where a_{i} is the ID number of a person in front of a student and b_{i} is the ID number of a person behind a student. The lines are given in the arbitrary order. Value 0 is given instead of a neighbor's ID number if the neighbor doesn't exist.

The ID numbers of all students are distinct. It is guaranteed that the records correspond too the queue where all the students stand in some order.


-----Output-----

Print a sequence of n integers x_1, x_2, ..., x_{n} — the sequence of ID numbers of all the students in the order they go in the queue from the first student to the last one.


-----Examples-----
Input
4
92 31
0 7
31 0
7 141

Output
92 7 31 141 



-----Note-----

The picture illustrates the queue for the first sample. [Image]

Difficulty: MEDIUM
Tags: Spanning trees

Implementation

Starter code:

Solutions:
a = int(input())
d = {}
dinv = {}
for i in range(a):
	b1 = input().split()
	b = list(b1)
	d[int(b[0])] = int(b[1])
	dinv[int(b[1])] = int(b[0])
c1 = []
n = 0
for i in range(a):
	n = d.get(n)
	if n in d and n != 0:
		c1 += [n]
	else:
		c1 += [n]
		break
c2 = []
for i in d.keys():
	if i not in dinv:
		k = i
		c2 += [k]
for i in range(a):
	k = d.get(k)
	if k in d and k != 0:
		c2 += [k]
	else:
		c2 += [k]
		break
c1 += [0]
c2 += [0]
for i in range(a):
	if c2[i] != 0:
		print(c2[i], end=' ')
	if c1[i] != 0:
		print(c1[i], end=' ')
	else:
		break


import sys
dic = {}
n = int(input())
for i in range(n):
	(a, b) = map(int, sys.stdin.readline().split())
	dic[a] = b
inv_dic = {v: k for (k, v) in dic.items()}
temp = dic.keys() - inv_dic.keys()
a = list(temp)[0]
b = 0
sys.stdout.write(str(a))
c = 0
for i in range(n - 1):
	if i % 2 == 0:
		c = dic[b]
		b = c
	else:
		c = dic[a]
		a = c
	sys.stdout.write(' ' + str(c))


n = int(input())
d = {}
d1 = {}
l = set()
ans = [0] * n
for i in range(n):
	(a, b) = map(int, input().split())
	d[a] = b
	d1[b] = a
	l.add(a)
	l.add(b)
i = 1
b = 0
l.remove(0)
while d.get(b, 0) != 0:
	b = d[b]
	l.remove(b)
	ans[i] = b
	i += 2
if n % 2 == 0:
	i = n - 2
	b = 0
	while d1.get(b, 0) != 0:
		b = d1[b]
		ans[i] = b
		i -= 2
else:
	for x in l:
		if d.get(x, -1) == -1:
			i = n - 1
			b = x
			while b != -1:
				ans[i] = b
				b = d1.get(b, -1)
				i -= 2
			break
print(*ans)


import sys
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
(n,) = I()
l = []
an = [0] * n
st = [-1] * (10 ** 6 + 1)
en = [-1] * (10 ** 6 + 1)
for i in range(n):
	(a, b) = I()
	st[a] = b
	en[b] = a
	if a == 0:
		an[1] = b
	if b == 0:
		an[n - 2] = a
	l.append([a, b])
for i in range(1, n - 2, 2):
	an[i + 2] = st[an[i]]
for i in range(n - 2, 1, -2):
	an[i - 2] = en[an[i]]
if n % 2:
	x = 0
	for i in range(1, len(st)):
		if st[i] != -1 and en[i] == -1:
			x = i
			break
	an[0] = x
	for i in range(0, n - 2, 2):
		an[i + 2] = st[an[i]]
print(*an)


x = int(input())
left = dict()
lset = set()
rset = set()
q = [0] * x
i = 0
while i < x:
	l = [int(j) for j in input().split()]
	left[l[0]] = l[1]
	lset.add(l[0])
	rset.add(l[1])
	i += 1
i = lset.difference(rset).pop()
j = 0
q[0] = i
k = 1
while k < x:
	q[k] = left[j]
	k += 1
	if k < x:
		q[k] = left[i]
	k += 1
	i = left[i]
	j = left[j]
print(' '.join([str(k) for k in q]))


n = int(input())
(d, d1) = ({}, {})
for i in range(n):
	(a, b) = map(int, input().split())
	(d[a], d1[b]) = (b, a)
res = []
for i in d.keys():
	if i not in d1:
		res.append(i)
res.append(d.get(0))
for i in range(2, n):
	res.append(d.get(res[i - 2]))
print(*res)


from collections import defaultdict
forth = defaultdict(lambda : None)
back = defaultdict(lambda : None)
eksist = defaultdict(lambda : None)

def line():
	return [int(c) for c in input().split()]
n = line()[0]
for _ in range(n):
	(l, r) = line()
	forth[l] = r
	back[r] = l
	eksist[l] = True
	eksist[r] = True
cursor = 0
oddList = []
while forth[cursor]:
	oddList.append(forth[cursor])
	eksist[forth[cursor]] = None
	cursor = forth[cursor]
if n % 2 == 0:
	cursor = 0
	evenList = []
	while back[cursor]:
		evenList.append(back[cursor])
		cursor = back[cursor]
	evenList = evenList[::-1]
	for i in range(n):
		if i % 2 == 0:
			print(evenList[i // 2], end=' ')
		if i % 2 == 1:
			print(oddList[i // 2], end=' ')
else:
	eksist[0] = None
	for k in list(eksist):
		if eksist[k]:
			cursor = k
			break
	evenList = []
	while back[cursor]:
		cursor = back[cursor]
	evenList.append(cursor)
	while forth[cursor]:
		evenList.append(forth[cursor])
		cursor = forth[cursor]
	for i in range(n):
		if i % 2 == 0:
			print(evenList[i // 2], end=' ')
		if i % 2 == 1:
			print(oddList[i // 2], end=' ')


from collections import *

class disjointset:

	def __init__(self, n):
		(self.parent, self.n, self.edges) = (defaultdict(lambda : -1), n, defaultdict(lambda : -1))

	def find(self, x):
		arr = [x]
		while self.edges[x] != -1:
			x = self.edges[x]
			arr.append(x)
		return arr

	def union(self, x, y):
		(self.parent[x], self.edges[y]) = (y, x)
(n, dis, nodes, arr1, arr2) = (int(input()), disjointset(0), defaultdict(int), deque([]), deque([]))
for i in range(n):
	(x, y) = map(float, input().split())
	if y != 0:
		dis.union(x, y)
		nodes[y] = 1
	nodes[x] = 1
for j in nodes:
	if dis.parent[j] == -1:
		a = dis.find(j)
		if a[-1] == 0:
			arr1 = deque(reversed(a))
		else:
			arr2 = deque(reversed(a))
arr1.popleft()
for i in range(n):
	if i % 2:
		print(int(arr1[0]), end=' ')
		arr1.popleft()
	else:
		print(int(arr2[0]), end=' ')
		arr2.popleft()


n = int(input())
List = [0] * (n + 1)
L = {}
R = {}
(l, r) = (0, 0)
front = 0
for i in range(n):
	(l, r) = list(map(int, input().split()))
	L.update({l: r})
	R.update({r: l})
List[2] = L[0]
i = 2
while i + 2 <= n:
	List[i + 2] = L[List[i]]
	i += 2
for k in L:
	if R.get(k) == None:
		front = k
		break
(i, List[1]) = (1, front)
while i + 2 <= n:
	List[i + 2] = L[List[i]]
	i += 2
print(*List[1:])


n = int(input())
after = {}
sets = [set(), set()]
for i in range(n):
	(a, b) = list(map(int, input().split()))
	sets[0].add(a)
	sets[1].add(b)
	after[a] = b
original_list = [0, (sets[0] - sets[1]).pop()]
for i in range(2, n + 2):
	original_list.append(after[original_list[i - 2]])
print(*original_list[1:n + 1])


(s1, s2, d, v) = (set(), set(), {}, [])
for _ in range(int(input())):
	(a, b) = map(int, input().split())
	d[a] = b
	s1.add(a)
	s2.add(b)
v.append(list(s1 - s2)[0])
v.append(d[0])
while 1:
	try:
		v.append(d[v[-2]])
		v.append(d[v[-2]])
	except:
		v.pop()
		print(*v)
		break


n = int(input())
d1 = dict()
d2 = dict()
ar = [0] * 30000000
for i in range(n):
	(a, b) = map(int, input().split())
	ar[a] += 1
	ar[b] += 1
	d1[a] = b
	d2[b] = a
if n % 2 == 0:
	x = 0
	ar1 = []
	ar2 = []
	while x in d1:
		ar1.append(d1[x])
		x = d1[x]
	x = 0
	while x in d2:
		ar2.append(d2[x])
		x = d2[x]
	ar2 = list(reversed(ar2))
	for i in range(len(ar2)):
		print(ar2[i], end=' ')
		print(ar1[i], end=' ')
else:
	arx = []
	for i in range(1000000):
		if ar[i] == 1:
			arx.append(i)
	a = arx[0]
	b = arx[1]
	if b in d2:
		(a, b) = (b, a)
	x = 0
	ar1 = []
	ar2 = []
	while x in d1:
		if d1[x] != 0:
			ar1.append(d1[x])
		x = d1[x]
		if x == 0:
			break
	x = a
	while x in d2:
		ar2.append(d2[x])
		x = d2[x]
	ar2 = list(reversed(ar2))
	for i in range(len(ar2)):
		print(ar2[i], end=' ')
		print(ar1[i], end=' ')
	print(a)


n = int(input())
(d, d1) = ({}, {})
for i in range(n):
	(a, b) = map(int, input().split())
	(d[a], d1[b]) = (b, a)
r = [list(filter(lambda f: d1.get(f) == None, d.keys()))[0], d.get(0)]
for i in range(2, n):
	r.append(d.get(r[i - 2]))
print(*r)


def last(i, find, finish):
	while dict_a[find] != finish:
		keys_a[i] = dict_a[find]
		find = keys_a[i]
		i += 2
n = int(input())
dict_a = {}
dict_b = {}
for i in range(n):
	c = input().split()
	dict_a[int(c[0])] = int(c[1])
	dict_b[int(c[1])] = None
keys_a = sorted(dict_a.keys())
dict_b = sorted(dict_b.keys())
pos = 0
while keys_a[pos] == dict_b[pos]:
	pos += 1
start = keys_a[pos]
end = dict_b[pos]
while pos + 1 < n and dict_b[pos + 1] == start:
	start = keys_a[pos + 1]
	pos += 1
while pos + 1 < n and keys_a[pos + 1] == end:
	end = dict_b[pos + 1]
	pos += 1
keys_a = [start] + [0] * (n - 2) + [end]
dict_b = None
if n % 2 == 0:
	last(2, start, 0)
	last(1, 0, end)
else:
	last(2, start, end)
	last(1, 0, 0)
for i in range(n - 1):
	print(keys_a[i], end=' ')
print(keys_a[n - 1])


n = int(input())
(A, B) = ({}, {})
for i in range(n):
	(a, b) = map(int, input().split())
	(A[a], B[b]) = (b, a)
t2 = A[0]
t1 = 0
for i in A.keys():
	try:
		B[i]
	except:
		t1 = i
		break
s = [t1, t2]
for i in range(n - 2):
	s.append(A[s[i]])
print(*s)


n = int(input())
front = {}
back = {}
for i in range(n):
	inp = tuple(map(int, input().split()))
	front[inp[0]] = inp[1]
	back[inp[1]] = inp[0]
fi = list(set(front) - set(back))[0]
e = []
i = 0
while i in front and front[i] != 0:
	e.append(front[i])
	i = front[i]
i = fi
o = [fi]
while i in front and front[i] != 0:
	o.append(front[i])
	i = front[i]
a = [0 for i in range(n + 1)]
for i in range(1, n + 1):
	if i % 2 != 0:
		a[i] = o[i // 2]
	else:
		a[i] = e[i // 2 - 1]
print(*a[1:])


n = int(input())
starts = [[0, 0]] * 1000001
ends = [[0, 0]] * 1000001
all_nums = set()
for i in range(n):
	pair = list(map(int, input().split()))
	starts[pair[0]] = pair
	ends[pair[1]] = pair
	all_nums.add(pair[0])
	all_nums.add(pair[1])
all_nums.remove(0)
ans = [0] * n
cur = starts[0]
i = 1
while cur[1] != 0:
	ans[i] = cur[1]
	cur = starts[cur[1]]
	all_nums.remove(ans[i])
	i += 2
e = all_nums.pop()
cur = starts[e]
tail = [e]
while cur[1] != 0:
	tail.append(cur[1])
	cur = starts[cur[1]]
head = []
cur = ends[tail[0]]
while cur[0] != 0:
	head.append(cur[0])
	cur = ends[cur[0]]
i = 0
for elem in reversed(head):
	ans[i] = elem
	i += 2
for elem in tail:
	ans[i] = elem
	i += 2
print(*ans)


import sys

def input():
	return sys.stdin.readline().strip()
n = int(input())
left = [-1] * (10 ** 6 + 1)
right = [-1] * (10 ** 6 + 1)
for i in range(n):
	(a, b) = map(int, input().split())
	left[a] = b
	right[b] = a
final = [0 for i in range(n)]
i = 1
cur = 0
while i < n:
	final[i] = left[cur]
	temp = left[cur]
	left[cur] = -1
	cur = temp
	i += 2
left[cur] = -1
if not n % 2:
	j = n - 2
	cur = 0
	while j >= 0:
		final[j] = right[cur]
		cur = right[cur]
		j -= 2
else:
	new = []
	for i in range(10 ** 6 + 1):
		if left[i] != -1:
			new.append(i)
	cur = 0
	for i in range(len(new)):
		if right[new[i]] == -1:
			cur = new[i]
			break
	final[0] = cur
	i = 2
	while i < n:
		final[i] = left[cur]
		cur = left[cur]
		i += 2
for i in range(n):
	print(final[i], end=' ')
print()


n = int(input())
(before, after) = ({}, {})
for i in range(n):
	(a, b) = map(int, input().split())
	after[a] = b
	before[b] = a
begin = None
for key in after.keys():
	if key not in before:
		begin = key
		break
sequence = n * [None]
for (pos, x) in [(0, begin), (1, after[0])]:
	while True:
		sequence[pos] = x
		if x not in after or after[x] == 0:
			break
		x = after[x]
		pos += 2
print(' '.join(map(str, sequence)))


n = int(input())
d = {}
t = {}
for i in range(n):
	(Qi, Pi) = list(map(int, input().split()))
	d[Qi] = Pi
	t[Pi] = Qi
ans = [list(filter(lambda x: t.get(x) == None, d.keys()))[0], d.get(0)]
for i in range(2, n):
	ans.append(d.get(ans[i - 2]))
print(*ans)


n = int(input())
m = []
l = {}
p = []
for i in range(n):
	t = list(map(int, input().split()))
	m.append([t[0], t[1]])
	l[t[0]] = t[1]
m.append([1000001, 1000001])
a = sorted(m, key=lambda x: x[0])
b = sorted(m, key=lambda x: x[1])
s = []
for i in range(0, n):
	if a[i][0] == b[i][1] and a[i + 1][0] != b[i + 1][1]:
		s.append(i + 1)
		if a[i + 2][0] == b[i + 2][1]:
			break
	if a[i][0] != b[i][1] and a[i + 1][0] == b[i + 1][1]:
		s.append(i)
if a[s[-1] - 1][0] == b[s[-1]][1]:
	u = s[0]
	s[0] = s[1]
	s[1] = u
j = n // 2
r = 0
e = a[s[0]][0]
if n % 2 == 0:
	for i in range(j):
		r = l[r]
		p.append(e)
		p.append(r)
		e = l[e]
if n % 2 != 0:
	p.append(e)
	for i in range(j):
		r = l[r]
		e = l[e]
		p.append(r)
		p.append(e)
print(' '.join(list((str(i) for i in p))))


from sys import stdin
n = int(input())
graph = {}
for _ in range(1, n + 1):
	(ai, bi) = input().split()
	graph[ai] = bi
ans = [0] * n
ans[0] = (set(graph.keys()) - set(graph.values())).pop()
ans[1] = graph['0']
for i in range(2, n):
	ans[i] = graph[ans[i - 2]]
print(*ans)


n = int(input())
graph = dict((input().split() for _ in range(n)))
ans = [None] * n
values = set(graph.values())
ans[0] = next((k for k in graph if k not in values))
ans[1] = graph['0']
for i in range(2, n):
	ans[i] = graph[ans[i - 2]]
print(*ans)


n = int(input())
findFirst = [0] * 1000001
posts = [-1] * 1000001
for i in range(0, n):
	(a, b) = map(int, input().split())
	posts[a] = b
	findFirst[a] += 1
	findFirst[b] -= 1
oddIndex = findFirst.index(1)
evenIndex = posts[0]
finalQueue = []
while True:
	finalQueue.append(oddIndex)
	finalQueue.append(evenIndex)
	oddIndex = posts[oddIndex]
	evenIndex = posts[evenIndex]
	if oddIndex == 0:
		break
	if evenIndex == 0:
		finalQueue.append(oddIndex)
		break
print(' '.join(list((str(i) for i in finalQueue))))


from sys import stdin, stdout
n = int(stdin.readline())
atob = {}
bs = set()
for i in range(n):
	(a, b) = stdin.readline().split()
	a = int(a)
	b = int(b)
	atob[a] = b
	bs.add(b)
queue = []
for ai in atob:
	if ai not in bs:
		queue.append(ai)
		break
queue.append(atob[0])
for i in range(2, n):
	queue.append(atob[queue[i - 2]])
print(*queue, sep=' ')


next_map = {}
key_set = set()
next_set = set()
n = int(input())
for i in range(n):
	(x, y) = map(int, input().split())
	key_set.add(x)
	key_set.add(y)
	next_set.add(y)
	next_map[x] = y
for x in key_set:
	if not x in next_set:
		first = x
next_map[-1] = first
res = [0 for i in range(n)]
x = 0
for i in range(n // 2):
	x = next_map[x]
	res[2 * i + 1] = x
x = -1
for i in range((n + 1) // 2):
	x = next_map[x]
	res[2 * i] = x
print(' '.join(map(str, res)))


from sys import stdin

def get_vital():
	for i in freq:
		if freq[i] == 1:
			start = i
		if freq[i] == -1:
			end = i
	return (start, end)
n = int(stdin.readline().strip())
freq = dict()
after = dict()
before = dict()
for _ in range(n):
	(first, second) = list(map(int, stdin.readline().split()))
	if first in freq:
		freq[first] += 1
	else:
		freq[first] = 1
	if second in freq:
		freq[second] -= 1
	else:
		freq[second] = -1
	after[first] = second
	before[second] = first
(start, eend) = get_vital()
arr = [-1] * n
arr[0] = start
arr[-1] = eend
start = 0
i = 1
while i < n:
	arr[i] = after[start]
	start = after[start]
	i += 2
end = 0
i = n - 2
while i > 0:
	arr[i] = before[end]
	end = before[end]
	i -= 2
if n % 2 == 1:
	end = arr[n - 1]
	i = n - 3
	while i > 0:
		arr[i] = before[end]
		end = before[end]
		i -= 2
print(*arr)


n = int(input())
(h, k) = ({}, {})
for i in range(n):
	(a, b) = map(int, input().split())
	h[a] = b
	k[b] = a
for i in h.keys():
	if i not in k.keys():
		head = i
		break
ans = head
ans1 = h[0]
i = 1
while ans != 0 and ans1 != 0:
	if i % 2 == 1:
		print(ans, end=' ')
		ans = h[ans]
	else:
		print(ans1, end=' ')
		ans1 = h[ans1]
	i += 1
if n % 2 == 1:
	print(ans)
else:
	print(ans1)


n = int(input())
dic = {}
ls = [[]] * n
left = [-1] * (int(1000000.0) + 1)
right = [-1] * (int(1000000.0) + 1)
for i in range(n):
	(a, b) = map(int, input().split())
	left[b] = a
	right[a] = b
val = right[0]
for i in range(1, n, 2):
	ls[i] = val
	val = right[val]
if not n % 2:
	val = left[max(val, 0)]
else:
	for i in range(len(left)):
		if left[i] != -1 and right[i] == -1:
			val = i
			break
for i in range(n - 1 - (not n % 2), -1, -2):
	ls[i] = val
	val = left[val]
print(*ls)


n = int(input())
s = [-1 for i in range(1000001)]
s1 = [-1 for i in range(1000001)]
for j in range(n):
	(pr, ne) = map(int, input().split())
	s[pr] = ne
	s1[ne] = pr
c = 0
ans1 = []
ans2 = []
while True:
	if s[c] == -1 or s[c] == 0:
		break
	else:
		ans1.append(s[c])
		c = s[c]
if s[c] == -1:
	c = 0
else:
	for i in range(1000001):
		if s[i] > 0 and s[s[i]] == -1:
			c = s[i]
			ans2.append(s[i])
			break
while True:
	if s1[c] == -1 or s1[c] == 0:
		break
	else:
		ans2.append(s1[c])
		c = s1[c]
ans2 = ans2[::-1]
ans = []
i = 0
(l1, l2) = (len(ans1), len(ans2))
while True:
	if i >= l1 and i >= l2:
		break
	elif i >= l1:
		ans.append(ans2[i])
	else:
		ans.append(ans2[i])
		ans.append(ans1[i])
	i += 1
print(' '.join(map(str, ans)))


n = int(input())
(after, before) = ({}, {})
for _ in range(n):
	(a, b) = map(int, input().split())
	(after[a], before[b]) = (b, a)
result = []
for i in after:
	if i not in before:
		result.append(i)
result.append(after.get(0))
for i in range(2, n):
	result.append(after.get(result[i - 2]))
print(*result)


n = int(input())
graph = {}
(A, B) = (set(), set())
for _ in range(1, n + 1):
	(ai, bi) = input().split()
	graph[ai] = bi
	A.add(ai)
	B.add(bi)
ans = [0] * n
ans[0] = (A - B).pop()
ans[1] = graph['0']
for i in range(2, n):
	ans[i] = graph[ans[i - 2]]
print(*ans)


import sys
sys.setrecursionlimit(10000000)
n = int(input())
father = [i for i in range(n + 1)]
children = [i for i in range(n + 1)]
i = 0
imap = 1
mapping = {'0': 0, 0: '0'}
while i < n:
	(a, b) = [i for i in input().split()]
	if not a in mapping:
		mapping[a] = imap
		mapping[imap] = a
		imap += 1
	if not b in mapping:
		mapping[b] = imap
		mapping[imap] = b
		imap += 1
	father[mapping[b]] = mapping[a]
	if b != 0:
		children[mapping[a]] = mapping[b]
	else:
		children[mapping[a]] = -1
	i += 1
i = 0
while father[i] != i:
	i += 1
queue = [mapping[i]]
first = i
i = 0
while father[i] != 0:
	i += 1
queue.append(mapping[i])
father[i] = -1
second = i
i = 0
while i < n - 2:
	if i % 2 == 0:
		first = children[first]
		queue.append(mapping[first])
	else:
		second = children[second]
		queue.append(mapping[second])
	i += 1
print(' '.join(queue))


n = int(input())
d = {}
s = [set(), set()]
for i in range(n):
	(a, b) = map(int, input().split())
	s[0].add(a)
	s[1].add(b)
	d[a] = b
res = [0, (s[0] - s[1]).pop()]
for i in range(2, n + 2):
	res.append(d[res[i - 2]])
print(*res[1:n + 1])


from collections import defaultdict, deque, Counter, OrderedDict
from bisect import insort, bisect_right, bisect_left
import threading, sys

def main():
	n = int(input())
	(adj, rdj) = ({}, {})
	ans = [0] * n
	for i in range(n):
		(a, b) = map(int, input().split())
		adj[a] = b
		rdj[b] = a
	(done, st, ind) = ({}, 0, 1)
	while ind < n:
		st = adj[st]
		ans[ind] = st
		done[st] = 1
		ind += 2
	(st, ind) = (0, n - 2)
	while ind >= 0:
		st = rdj[st]
		ans[ind] = st
		ind -= 2
	if n % 2:
		nd = 0
		for k in adj:
			if k not in done and k != 0:
				nd = k
				break
		while nd in rdj:
			nd = rdj[nd]
		for i in range(n):
			if ans[i] == 0:
				ans[i] = nd
				nd = adj.get(nd, 0)
	print(' '.join(map(str, ans)))
thread = threading.Thread(target=main)
thread.start()


n = int(input())
maxn = 10 ** 6 + 1
nxt = [0] * maxn
nxta = [0] * maxn
ans = [0] * n
used = [0] * maxn
for i in range(n):
	(x, y) = map(int, input().split())
	if x == 0:
		s = i
	nxta[x] = i
	nxt[i] = y
	used[x] += 1
	used[y] += 2
for i in range(maxn):
	if used[i] == 1:
		z = i
for i in range(n):
	ans[i] = z
	(z, s) = (nxt[s], nxta[z])
for i in ans:
	print(i, end=' ')


n = int(input())
a = []
b = []
for i in range(n):
	(p, q) = (int(x) for x in input().split())
	a.append(p)
	b.append(q)
d = dict(zip(a, b))
first = (set(a) - set(b)).pop()
second = d[0]
res = []
for i in range(n - 2):
	res.append(str(first))
	(first, second) = (second, d[first])
print(' '.join(res), first, second)


from sys import stdin
test_lines = map(str.strip, stdin.readlines())
n = int(next(test_lines))
graph = {}
(a, b) = (set(), set())
for _ in range(1, n + 1):
	(ai, bi) = next(test_lines).split()
	graph[ai] = bi
	a.add(ai)
	b.add(bi)
ans = [(a - b).pop(), graph['0']]
for i in range(2, n):
	ans.append(graph[ans[i - 2]])
print(*ans)


def findback(fronts, backs):
	count = dict()
	nums = fronts + backs
	for i in nums:
		if i not in count:
			count[i] = 1
		else:
			count[i] += 1
	res = -1
	for i in nums:
		if count[i] == 1 and i in backs:
			res = i
			break
	return res
n = int(input())
forward = [-1 for _ in range(int(1000000.0 + 1))]
backward = [-1 for _ in range(int(1000000.0 + 1))]
fronts = []
backs = []
for _ in range(n):
	(front, back) = (int(x) for x in input().split())
	forward[front] = back
	backward[back] = front
	fronts.append(front)
	backs.append(back)
ans = [None for i in range(n)]
idx = forward[0]
i = 1
while i < n:
	ans[i] = idx
	i += 2
	idx = forward[idx]
if n % 2 == 1:
	idx = findback(fronts, backs)
	i = n - 1
else:
	idx = backward[0]
	i = n - 2
while i >= 0:
	ans[i] = idx
	i -= 2
	idx = backward[idx]
print(*(i for i in ans))


n = int(input())
m = {}
a = []
for i in range(n):
	(f, b) = [int(k) for k in input().split()]
	m[f] = b
	a.append(b)
ans = list(set(m.keys()) - set(a))
ans.append(m.get(0))
for i in range(n - 2):
	ans.append(m.get(ans[i]))
print(*ans)


from collections import *
n = int(input())
d = {}
c = Counter()
for i in range(n):
	(a, b) = map(int, input().split())
	d[a] = [a, b]
	c[a] += 1
	c[b] += 1
ans = [x for x in c if c[x] == 1 and d.get(x, []) != []] + d[0][1:]
for i in range(n - 2):
	ans += d[ans[i]][1:]
print(' '.join(map(str, ans)))


n = int(input())
from sys import stdin
item = lambda : stdin.readline().split()
(d, di) = ({}, {})
for _ in range(n):
	(a, b) = map(int, item())
	d[a] = b
	if di.get(a) == None:
		di[a] = 0
	if di.get(b) == None:
		di[b] = 0
	di[a] += 1
	di[b] += 1
lst = []
for (i, x) in enumerate(di):
	if di[x] == 1:
		lst.append(x)
res = [0] * n
if d.get(lst[0]) != None:
	(res[0], res[-1]) = (lst[0], lst[1])
else:
	(res[0], res[-1]) = (lst[1], lst[0])
d[res[-1]] = -1
(i, x) = (0, res[0])
while i < n:
	res[i] = x
	x = d[x]
	i += 2
(i, x) = (1, d[0])
while i < n:
	res[i] = x
	x = d[x]
	i += 2
print(*res)


__author__ = 'Rakshak.R.Hegde'
n = int(input())
m = dict()
s = [0] * (2 * n)
xor2 = 0
ind = 0
for i in range(n):
	(a, b) = map(int, input().split())
	xor2 ^= a ^ b
	s[ind] = a
	ind += 1
	s[ind] = b
	ind += 1
	m[a] = b
l = r = 0
setBit = xor2 & ~(xor2 - 1)
for i in s:
	if i & setBit:
		l ^= i
	else:
		r ^= i
if l not in m:
	l = r
(a, b) = (0, l)
ans = str(b)
for i in range(1, n, 2):
	a = m[a]
	ans += ' ' + str(a)
	b = m[b]
	if b != 0:
		ans += ' ' + str(b)
print(ans)


n = int(input())
m = {}
B = []
for j in range(n):
	(a, b) = [int(i) for i in input().split()]
	m[a] = b
	B.append(b)
ans = list(set(m.keys()) - set(B))
ans.append(m.get(0))
for i in range(n - 2):
	ans.append(m.get(ans[i]))
print(*ans)


n = int(input())
d = {}
d1 = {}
f = []
for i in range(n):
	(a, b) = [int(i) for i in input().split()]
	d[a] = b
	d1[b] = a
	f.append(a)
l = [None] * n
for i in f:
	try:
		x = d1[i]
	except KeyError:
		l[0] = i
		break
l[1] = d[0]
for i in range(2, n):
	l[i] = d[l[i - 2]]
s = ''
for i in range(n):
	l[i] = str(l[i])
print(' '.join(l))


n = int(input())
h = {}
f = {}
arr = []
t = 0
for i in range(n):
	(a, b) = [int(i) for i in input().split()]
	h[a] = b
	f[b] = a
for i in h.keys():
	if i not in f.keys():
		arr.append(i)
		break
arr.append(h[0])
for i in range(n - 2):
	arr.append(h[arr[i]])
print(' '.join(list((str(i) for i in arr))))


n = int(input())
line = [None] * n
(first, second) = ({}, {})
for i in range(n):
	(pre, suc) = [int(num) for num in input().split()]
	first[pre] = suc
	second[suc] = pre
	if pre == 0:
		line[0] = (pre, suc)
for i in first:
	if i != 0 and i not in second:
		line[1] = (i, first[i])
		break
for i in range(n - 2):
	line[i + 2] = (line[i][1], first[line[i][1]])
print(line[1][0], end=' ')
for i in range(n - 1):
	if i != n - 2:
		print(line[i][1], end=' ')
	else:
		print(line[i][1])


next = {}
appear = {}
front = {}
n = int(input())
for i in range(1, n + 1):
	[a, b] = [int(x) for x in input().split()]
	next[a] = b
	front[a] = True
	front[b] = False
	if a not in appear:
		appear[a] = 1
	else:
		appear[a] = 2
	if b not in appear:
		appear[b] = 1
	else:
		appear[b] = 2
a = 0
b = 0
for x in appear.keys():
	if appear[x] == 1 and front[x]:
		print(x, next[0], end=' ')
		a = x
		b = next[0]
cnt = 2
for i in range(0, n - 1):
	if cnt == n:
		break
	print(next[a], end=' ')
	cnt += 1
	if cnt == n:
		break
	print(next[b], end=' ')
	cnt += 1
	if cnt == n:
		break
	a = next[a]
	b = next[b]
print()


import sys
from math import *

def minp():
	return sys.stdin.readline().strip()

def mint():
	return int(minp())

def mints():
	return map(int, minp().split())
n = mint()
l = [0] * (10 ** 6 + 1)
r = [0] * (10 ** 6 + 1)
all = [0] * (2 * n)
k1 = None
k2 = None
for i in range(n):
	(a, b) = mints()
	l[b] = a
	r[a] = b
	all[i * 2] = a
	all[i * 2 + 1] = b
	if a == 0:
		k1 = b
	if b == 0:
		k2 = a
z = k1
q = []
x = z
w = [False] * (10 ** 6 + 1)
w[0] = True
while x != 0:
	q.append(x)
	w[x] = True
	x = r[x]
Q = []
if k2 == q[-1]:
	for i in all:
		if not w[i]:
			x = i
			while l[x] != 0:
				x = l[x]
			while x != 0:
				Q.append(x)
				x = r[x]
			break
else:
	z = k2
	x = z
	while x != 0:
		Q.append(x)
		x = l[x]
	Q = Q[::-1]
i = 0
j = 0
k = 0
R = [0] * n
while i < len(q) or j < len(Q):
	if j < len(Q):
		R[k] = Q[j]
		k += 1
		j += 1
	if i < len(q):
		R[k] = q[i]
		k += 1
		i += 1
print(*R)


n = int(input())
right = {}
left = {}
numbers = set()
for _ in range(n):
	(u, v) = list(map(lambda x: int(x), input().split()))
	right[u] = v
	left[v] = u
	numbers.add(v)
	numbers.add(u)
start = 0
a = [0 for _ in range(n)]
i = 1
while start in right and i <= n - 1:
	start = right[start]
	a[i] = start
	i += 2
end = 0
i = n - 2
while end in left and i >= 0:
	end = left[end]
	a[i] = end
	i -= 2
if a[0] == 0:
	values = set(list(right.values()))
	first = -1
	for number in numbers:
		if number not in values:
			first = number
			break
	start = first
	i = 2
	a[0] = first
	while start in right and i <= n - 1:
		start = right[start]
		a[i] = start
		i += 2
for i in a:
	print(i, end=' ')


n = int(input())
ID = 1000001
thprev = [-1 for i in range(ID)]
thpost = [-1 for i in range(ID)]
prev = []
post = []
for i in range(n):
	(a, b) = [int(s) for s in input().split()]
	prev.append(a)
	post.append(b)
	thprev[a] = i
	thpost[b] = i
sth = thprev[0]
v = post[sth]
q1 = []
while v > 0 and sth >= 0:
	q1.append(v)
	sth = thprev[v]
	v = post[sth]
start1 = thprev[0]
for i in range(n):
	if i != start1 and thpost[prev[i]] == -1:
		start2 = i
		break
sth = start2
u = prev[sth]
v = post[sth]
q2 = [u]
while v > 0 and sth >= 0:
	q2.append(v)
	sth = thprev[v]
	v = post[sth]
q1.reverse()
q2.reverse()
q = []
label = 2
while q1 or q2:
	if label == 1:
		q.append(q1.pop())
		label = 2
	else:
		q.append(q2.pop())
		label = 1
print(' '.join(map(str, q)))


(u, v, n) = ({}, {}, int(input()))
for i in range(n):
	(a, b) = input().split()
	u[a] = b
	v[b] = a
(x, y) = (u['0'], v['0'])
if n & 1:
	for y in v:
		if not y in u:
			break
(a, b) = ([x], [y])
k = n // 2
for i in range(k - 1):
	(x, y) = (u[x], v[y])
	a.append(x)
	b.append(y)
if n & 1:
	b.append(v[y])
b.reverse()
t = []
for i in range(k):
	t.append(b[i])
	t.append(a[i])
if n & 1:
	t.append(b[k])
print(' '.join(t))


n = int(input())
d = {}
f_list = []
s = set()
for i in range(n):
	(first, second) = map(str, input().split(' '))
	d[first] = second
	f_list.append(first)
	s.add(second)
first = ''
for x in f_list:
	if x not in s:
		first = x
		break
answer = []
answer.append(first)
answer.append(d['0'])
for i in range(n - 2):
	counter = i + 2
	answer.append(d[answer[counter - 2]])
print(' '.join(answer))


import sys
inp = sys.stdin
n = int(inp.readline())
after = [-1] * (10 ** 6 + 1)
before = [-1] * (10 ** 6 + 1)
used = [0] * (10 ** 6 + 1)
for i in range(n):
	(x, y) = map(int, inp.readline().split())
	after[x] = y
	before[y] = x
	used[x] = used[y] = 1
ans = [0] * n
i = 1
x = 0
while after[x] > 0:
	x = after[x]
	ans[i] = x
	i += 2
for i in range(10 ** 6 + 1):
	if used[i] == 1 and before[i] == -1:
		x = i
		break
i = 0
while i < n and x > 0:
	ans[i] = x
	i += 2
	x = after[x]
for i in ans:
	print(i, end=' ')


n = int(input())
seq = dict()
result = [0] * n
time = dict()
length = n
for i in range(n):
	tem = [int(i) for i in input().split()]
	seq[tem[0]] = tem[1]
	if tem[0] not in time:
		time[tem[0]] = 1
	else:
		time[tem[0]] = 2
	if tem[1] not in time:
		time[tem[1]] = 0
	else:
		time[tem[1]] = 2
for item in time:
	if time[item] == 1:
		result[0] = item
		k = item
j = seq[0]
result[1] = j
bound = n // 2 + 1
if n > 2:
	for i in range(1, bound):
		result[2 * i] = seq[k]
		k = seq[k]
		if seq[j] == 0:
			break
		result[2 * i + 1] = seq[j]
		j = seq[j]
		if seq[k] == 0:
			break
for m in range(0, len(result)):
	print(result[m], end=' ')


n = int(input())
graph = dict([input().split() for _ in range(n)])
ans = [0] * n
ans[0] = (set(graph.keys()) - set(graph.values())).pop()
ans[1] = graph['0']
for i in range(2, n):
	ans[i] = graph[ans[i - 2]]
print(*ans)


from sys import stdin
test_lines = map(str.strip, stdin.readlines())
n = int(next(test_lines))
graph = {}
for _ in range(1, n + 1):
	(ai, bi) = next(test_lines).split()
	graph[ai] = bi
ans = [-1] * n
first = (set(graph.keys()) - set(graph.values())).pop()
ans[0] = first
ans[1] = graph['0']
for i in range(2, n):
	ans[i] = graph[ans[i - 2]]
print(*ans)


(ab, ba, n) = ({}, {}, int(input()))
res = [None] * n
for _ in range(n):
	(a, b) = input().split()
	(ab[a], ba[b]) = (b, a)
x = '0'
for i in range(1, n, 2):
	res[i] = x = ab[x]
if n & 1:
	n += 1
	for x in ba:
		if x not in ab:
			ba['0'] = x
			break
x = '0'
for i in range(n - 2, -1, -2):
	res[i] = x = ba[x]
print(' '.join(res))


n = int(input())
Queue = [0] * n
Dic0 = {}
Dic1 = {}
Bucket = [0] * 1000001
for i in range(n):
	t = list(map(int, input().split()))
	Dic0[t[0]] = t[1]
	Dic1[t[1]] = t[0]
	Bucket[t[0]] -= 1
	Bucket[t[1]] += 1
Queue[0] = i = Bucket.index(-1)
Queue[1] = j = Dic0[0]
L = 1
while True:
	if L + 1 >= n:
		break
	Queue[L + 1] = Dic0[i]
	i = Dic0[i]
	if L + 2 < n:
		Queue[L + 2] = Dic0[j]
		j = Dic0[j]
	L += 2
print(' '.join(map(str, Queue)))


def main():
	n = int(input())
	(dl, dr) = (dict(), dict())
	for i in range(n):
		(a, b) = map(int, input().split())
		(dr[a], dl[b]) = (b, a)
	for i in dr:
		if dl.get(i) is None:
			st = i
			break
	ans = [st, dr[0]]
	for i in range(2, n):
		ans.append(dr[ans[i - 2]])
	print(*ans)
main()


from sys import stdin, stdout
fin = stdin
fout = stdout
n = int(fin.readline().rstrip())
q = []
d = dict()
a = dict()
for i in range(n):
	q.append(list(map(int, fin.readline().split())))
	a[q[i][0]] = q[i][1]
	if q[i][0] not in d:
		d[q[i][0]] = 0
	d[q[i][0]] += 1
	if q[i][1] not in d:
		d[q[i][1]] = 0
	d[q[i][1]] += 1
ans = [0, 0]
for key in d.keys():
	if d[key] == 1:
		for i in range(n):
			if key == q[i][0]:
				ans[0] = key
			if 0 == q[i][0]:
				ans[1] = q[i][1]
fout.write(' '.join(map(str, (ans[0], ans[1]))))
for i in range(2, n):
	ans.append(a[ans[i - 2]])
	fout.write(' ' + str(a[ans[i - 2]]))


first = set()
second = set()
map = {}
n = int(input())
for i in range(n):
	temp = input().split()
	first.add(int(temp[0]))
	second.add(int(temp[1]))
	map[int(temp[0])] = int(temp[1])
temp = 0
res = [temp for x in range(n + 10)]
j = 2
temp = 0
while temp in map.keys():
	if j > n + 1:
		break
	temp = map[temp]
	res[j] = temp
	j += 2
x = first - second
temp = int(x.pop())
j = 1
while temp != 0:
	res[j] = temp
	j += 2
	try:
		temp = map[temp]
	except:
		break
for (i, x) in enumerate(res):
	if i < n + 1:
		if i != 0:
			print(x, end=' ')


n = int(input())
(d, ans) = ({}, [None] * n)
for _ in range(n):
	(p, q) = map(int, input().split())
	d[p] = q
s = list(set(d.keys()) - set(d.values()))
(l, r) = (s, [0])
while len(l) < n // 2 + n % 2:
	l.append(d[l[-1]])
while len(r) < n // 2 + 1:
	r.append(d[r[-1]])
(ans[::2], ans[1::2]) = (l, r[1:])
print(' '.join(map(str, ans)))


def main():
	mode = 'filee'
	if mode == 'file':
		f = open('test.txt', 'r')
	get = lambda : [int(x) for x in (f.readline() if mode == 'file' else input()).split()]
	[n] = get()
	front = {}
	back = {}
	a = [0] * (n + 2)
	for z in range(n):
		[x, y] = get()
		front[x] = y
		back[y] = x
	prev = 0
	front_set = set(front.keys())
	back_set = set(back.keys())
	start = (front_set - back_set).pop()
	for i in range(2, n + 1, 2):
		a[i] = front[prev]
		prev = a[i]
	[a[1], prev] = [start, start]
	for i in range(3, n + 1, 2):
		a[i] = front[prev]
		prev = a[i]
	for i in a[1:-1]:
		print(i, end=' ')
	if mode == 'file':
		f.close()
main()


n = int(input())
d = {}
d1 = {}
for i in range(n):
	(a, b) = list(map(int, input().split()))
	d[a] = b
	d1[b] = a
r = [0] * n
front = 0
i = 1
while i < n:
	r[i] = d.get(front)
	front = r[i]
	i += 2
for f in list(d.keys()):
	if d1.get(f) == None:
		front = f
		break
r[0] = front
i = 2
while i < n:
	r[i] = d.get(front)
	front = r[i]
	i += 2
print(*r)


import sys
import math
from collections import defaultdict
import itertools
MAXNUM = math.inf
MINNUM = -1 * math.inf

def getInts():
	return map(int, sys.stdin.readline().rstrip().split(' '))

def getString():
	return sys.stdin.readline().rstrip()

def printOutput(ans):
	sys.stdout.write()
	pass

def solve():
	pass

def readinput():
	students = int(sys.stdin.readline().rstrip())
	idNumbers = {}
	singles = set()
	for _ in range(students):
		(prev, nxt) = getInts()
		if prev not in idNumbers:
			singles.add(prev)
			idNumbers[prev] = [0, nxt]
		else:
			singles.remove(prev)
			idNumbers[prev][1] = nxt
		if nxt not in idNumbers:
			idNumbers[nxt] = [prev, 0]
			singles.add(nxt)
		else:
			singles.remove(nxt)
			idNumbers[nxt][0] = prev
	ans = list(singles)
	if idNumbers[ans[0]][0] == 0:
		start = ans[0]
	else:
		start = ans[1]
	second = idNumbers[0][1]
	ans = []
	ans.append(start)
	ans.append(second)
	cur1 = start
	cur2 = second
	while idNumbers[cur1][1] != 0 or idNumbers[cur2][1] != 0:
		if idNumbers[cur1][1] != 0:
			cur1 = idNumbers[cur1][1]
			ans.append(cur1)
		if idNumbers[cur2][1] != 0:
			cur2 = idNumbers[cur2][1]
			ans.append(cur2)
	if len(idNumbers) == 3:
		ans = [idNumbers[0][0], idNumbers[0][1]]
	for ele in ans:
		print(ele, end=' ')
readinput()


import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n = int(input())
d = {}
ddd = {}
dd = {}
for i in range(n):
	(a, b) = map(int, input().split())
	d[a] = b
	dd[b] = a
	if a in ddd:
		ddd.pop(a)
	else:
		ddd[a] = 1
	if b in ddd:
		ddd.pop(b)
	else:
		ddd[b] = -1
temp = 0
ind = 1
a = [0] * n
while temp in d:
	temp = d[temp]
	if temp == 0:
		break
	a[ind] = temp
	ind += 2
if len(a) & 1:
	ind = len(a) - 1
	temp = 0
	tempp = 0
	for x in ddd:
		if ddd[x] == -1:
			temp = x
		else:
			tempp = x
	while temp in dd:
		a[ind] = temp
		temp = dd[temp]
		ind -= 2
	a[0] = tempp
else:
	ind = len(a) - 2
	temp = 0
	while temp in dd:
		temp = dd[temp]
		if temp == 0:
			break
		a[ind] = temp
		ind -= 2
print(*a)


readints = lambda : map(int, input().strip('\n').split())
n = int(input())

def printlist(lst):
	buf = ''
	for i in range(len(lst) - 1):
		buf += str(lst[i]) + ' '
	buf += str(lst[-1])
	print(buf)

def findFirstStudent(students):
	behindSet = set()
	for (front, behind) in students:
		behindSet.add(behind)
	for (front, _) in students:
		if front not in behindSet:
			return front

def reconstructLine(students):
	n = len(students)
	line = [0] * n
	frontToBehind = {}
	for (front, behind) in students:
		frontToBehind[front] = behind
	line[0] = findFirstStudent(students)
	line[1] = frontToBehind[0]
	for i in range(2, n):
		line[i] = frontToBehind[line[i - 2]]
	return line
students = [tuple(readints()) for _ in range(n)]
printlist(reconstructLine(students))


n = int(input())
pairs = {}
for i in range(n):
	(before, behind) = [int(x) for x in input().split()]
	pairs[before] = behind
curr = 0
even = [curr]
while curr in pairs and pairs[curr] > 0:
	curr = pairs[curr]
	even.append(curr)
rev_pairs = {}
for before in pairs:
	behind = pairs[before]
	rev_pairs[behind] = before
for curr in rev_pairs:
	if curr not in even:
		break
	elif rev_pairs[curr] not in even:
		curr = rev_pairs[curr]
		break
while curr in rev_pairs and rev_pairs[curr] > 0:
	curr = rev_pairs[curr]
odd = [curr]
while curr in pairs and pairs[curr] > 0:
	curr = pairs[curr]
	odd.append(curr)
for i in range(n // 2):
	print(odd[i], even[i + 1], end=' ')
if n % 2 != 0:
	print(odd[n // 2], end=' ')
print()


N = 1000010
a = [0] * N
b = [0] * N
ans = [0] * N
vis = [0] * N
tmp = [0] * N
n = int(input())
for i in range(1, n + 1):
	temp = input().split(' ')
	fr = int(temp[0])
	ba = int(temp[1])
	a[fr] = ba
	b[ba] = fr
	vis[fr] = vis[ba] = 1
k = 2
i = a[0]
while i != 0:
	ans[k] = i
	vis[i] = 0
	i = a[i]
	k += 2
k = 1
while True:
	if vis[k] != 0:
		break
	k += 1
while b[k] != 0:
	k = b[k]
fzc = k
k = 1
i = fzc
while i != 0:
	ans[k] = i
	i = a[i]
	k += 2
print(' '.join(map(str, ans[1:n + 1])))


import math
from collections import deque

class Empty(Exception):
	pass

class _DoublyLinkedBase:

	class _Node:
		__slots__ = ('_element', '_prev', '_next')

		def __init__(self, element, prev, next):
			self._element = element
			self._prev = prev
			self._next = next

	def __init__(self):
		self._header = self._Node(None, None, None)
		self._trailer = self._Node(None, None, None)
		self._header._next = self._trailer
		self._trailer._prev = self._header
		self._size = 0

	def __len__(self):
		return self._size

	def is_empty(self):
		return self._size == 0

	def _insert_between(self, e, predecessor, successor):
		newest = self._Node(e, predecessor, successor)
		predecessor._next = newest
		successor._prev = newest
		self._size += 1
		return newest

	def _delete_node(self, node):
		predecessor = node._prev
		successor = node._next
		predecessor._next = successor
		successor._prev = predecessor
		self._size -= 1
		element = node._element
		node._prev = node._next = node._element = None
		return element

class LinkedDeque(_DoublyLinkedBase):

	def first(self):
		if self.is_empty():
			raise Empty('Deque is empty')
		return self._header._next._element

	def last(self):
		if self.is_empty():
			raise Empty('Deque is empty')
		return self._trailer._prev._element

	def insert_first(self, e):
		self._insert_between(e, self._header, self._header._next)

	def insert_last(self, e):
		self._insert_between(e, self._trailer._prev, self._trailer)

	def delete_first(self):
		if self.is_empty():
			raise Empty('Deque is empty')
		return self._delete_node(self._header._next)

	def delete_last(self):
		if self.is_empty():
			raise Empty('Deque is empty')
		return self._delete_node(self._trailer._prev)

class PositionalList(_DoublyLinkedBase):

	class Position:

		def __init__(self, container, node):
			self._container = container
			self._node = node

		def element(self):
			return self._node._element

		def __eq__(self, other):
			return type(other) is type(self) and other._node is self._node

		def __ne__(self, other):
			return not self == other

	def _validate(self, p):
		if not isinstance(p, self.Position):
			raise TypeError('p must be proper Position type')
		if p._container is not self:
			raise ValueError('p does not belong to this container')
		if p._node._next is None:
			raise ValueError('p is no longer valid')
		return p._node

	def _make_position(self, node):
		if node is self._header or node is self._trailer:
			return None
		else:
			return self.Position(self, node)

	def first(self):
		return self._make_position(self._header._next)

	def last(self):
		return self._make_position(self._trailer._prev)

	def before(self, p):
		node = self._validate(p)
		return self._make_position(node._prev)

	def after(self, p):
		node = self._validate(p)
		return self._make_position(node._next)

	def __iter__(self):
		cursor = self.first()
		while cursor is not None:
			yield cursor.element()
			cursor = self.after(cursor)

	def _insert_between(self, e, predecessor, successor):
		node = super()._insert_between(e, predecessor, successor)
		return self._make_position(node)

	def add_first(self, e):
		return self._insert_between(e, self._header, self._header._next)

	def add_last(self, e):
		return self._insert_between(e, self._trailer._prev, self._trailer)

	def add_before(self, p, e):
		original = self._validate(p)
		return self._insert_between(e, original._prev, original)

	def add_after(self, p, e):
		original = self._validate(p)
		return self._insert_between(e, original, original._next)

	def delete(self, p):
		original = self._validate(p)
		return self._delete_node(original)

	def replace(self, p, e):
		original = self._validate(p)
		old_value = original._element
		original._element = e
		return old_value
L1 = LinkedDeque()
L2 = LinkedDeque()
dic = {}
dic2 = {}
n = int(input())
for i in range(n):
	(a, b) = (int(i) for i in input().split())
	dic[a] = b
	dic2[b] = a
forw = 0
while forw in dic:
	L1.insert_last(dic[forw])
	t = dic[forw]
	dic.pop(forw)
	forw = t
if L1.last() == 0:
	L1.delete_last()
if n % 2 == 0:
	backw = 0
	while backw in dic2:
		L2.insert_first(dic2[backw])
		t = dic2[backw]
		dic2.pop(backw)
		backw = t
else:
	(tk, tv) = (0, 0)
	for (k, v) in dic.items():
		tk = k
		tv = v
	forw = tk
	while forw in dic:
		L2.insert_last(dic[forw])
		t = dic[forw]
		dic.pop(forw)
		forw = t
	backw = tv
	while backw in dic2:
		L2.insert_first(dic2[backw])
		t = dic2[backw]
		dic2.pop(backw)
		backw = t
outList = []
while L1.is_empty() == False:
	outList.append(str(L2.first()))
	outList.append(str(L1.first()))
	L1.delete_first()
	L2.delete_first()
if L2.is_empty() == False:
	outList.append(str(L2.first()))
	pass
print(' '.join(outList))


n = int(input())
(a, b) = ([], [])
for i in range(n):
	(x, y) = map(int, input().split())
	a.append(x)
	b.append(y)
s1 = set(a)
s2 = set(b)
ans = [-1] * n
for i in s1:
	if i not in s2:
		ans[0] = i
		break
for i in s2:
	if i not in s1:
		ans[-1] = i
		break
d = {}
for i in range(n):
	d[a[i]] = b[i]
ans[1] = d[0]
for i in range(2, n - 1):
	ans[i] = d[ans[i - 2]]
print(*ans)


import math
from collections import deque

class Empty(Exception):
	pass

class _DoublyLinkedBase:

	class _Node:
		__slots__ = ('_element', '_prev', '_next')

		def __init__(self, element, prev, next):
			self._element = element
			self._prev = prev
			self._next = next

	def __init__(self):
		self._header = self._Node(None, None, None)
		self._trailer = self._Node(None, None, None)
		self._header._next = self._trailer
		self._trailer._prev = self._header
		self._size = 0

	def __len__(self):
		return self._size

	def is_empty(self):
		return self._size == 0

	def _insert_between(self, e, predecessor, successor):
		newest = self._Node(e, predecessor, successor)
		predecessor._next = newest
		successor._prev = newest
		self._size += 1
		return newest

	def _delete_node(self, node):
		predecessor = node._prev
		successor = node._next
		predecessor._next = successor
		successor._prev = predecessor
		self._size -= 1
		element = node._element
		node._prev = node._next = node._element = None
		return element

class LinkedDeque(_DoublyLinkedBase):

	def first(self):
		if self.is_empty():
			raise Empty('Deque is empty')
		return self._header._next._element

	def last(self):
		if self.is_empty():
			raise Empty('Deque is empty')
		return self._trailer._prev._element

	def insert_first(self, e):
		self._insert_between(e, self._header, self._header._next)

	def insert_last(self, e):
		self._insert_between(e, self._trailer._prev, self._trailer)

	def delete_first(self):
		if self.is_empty():
			raise Empty('Deque is empty')
		return self._delete_node(self._header._next)

	def delete_last(self):
		if self.is_empty():
			raise Empty('Deque is empty')
		return self._delete_node(self._trailer._prev)
L1 = LinkedDeque()
L2 = LinkedDeque()
dic = {}
dic2 = {}
n = int(input())
for i in range(n):
	(a, b) = (int(i) for i in input().split())
	dic[a] = b
	dic2[b] = a
forw = 0
while forw in dic:
	L1.insert_last(dic[forw])
	t = dic[forw]
	dic.pop(forw)
	forw = t
if L1.last() == 0:
	L1.delete_last()
if n % 2 == 0:
	backw = 0
	while backw in dic2:
		L2.insert_first(dic2[backw])
		t = dic2[backw]
		dic2.pop(backw)
		backw = t
else:
	(tk, tv) = (0, 0)
	for (k, v) in dic.items():
		tk = k
		tv = v
	forw = tk
	while forw in dic:
		L2.insert_last(dic[forw])
		t = dic[forw]
		dic.pop(forw)
		forw = t
	backw = tv
	while backw in dic2:
		L2.insert_first(dic2[backw])
		t = dic2[backw]
		dic2.pop(backw)
		backw = t
outList = []
while L1.is_empty() == False:
	outList.append(str(L2.first()))
	outList.append(str(L1.first()))
	L1.delete_first()
	L2.delete_first()
if L2.is_empty() == False:
	outList.append(str(L2.first()))
	pass
print(' '.join(outList))


n = int(input())
(d, f) = ({}, {})
ans = [0] * n
for i in range(n):
	(a, b) = map(int, input().split())
	(d[a], f[b]) = (b, a)
	if a == 0:
		ans[1] = b
	if b == 0:
		ans[-2] = a
(i, c) = (1, ans[1])
while 1:
	if i + 2 > n - 1:
		break
	x = d[c]
	c = x
	i += 2
	ans[i] = x
if n % 2 == 0:
	(i, c) = (n - 2, ans[-2])
	while 1:
		if i - 2 < 0:
			break
		x = f[c]
		c = x
		i -= 2
		ans[i] = x
	print(*ans)
else:
	for i in d:
		if i not in f:
			ans[0] = i
			break
	(i, c) = (0, ans[0])
	while 1:
		if i + 2 > n - 1:
			break
		x = d[c]
		c = x
		i += 2
		ans[i] = x
	print(*ans)


n = int(input())
s = dict()
for i in range(n):
	(a, b) = [int(element) for element in input().split(' ')]
	s[a] = b
v = []
v.append(0)
t = set(s.values())
for key in s.keys():
	if key not in t:
		v.append(key)
		break
for i in range(n - 1):
	v.append(s[v[-2]])
v = [str(elem) for elem in v]
print(' '.join(v[1:]))


def main():
	n = int(input())
	if n % 2 == 1:
		s = {}
		s1 = {}
		a = [0] * n
		start = 0
		finish = 0
		set1 = set()
		set2 = set()
		for i in range(n):
			(x, y) = map(int, input().split())
			set1.add(x)
			set2.add(y)
			if x == 0:
				start = y
				s[x] = y
				s1[y] = x
			elif y == 0:
				finish = x
				s[x] = y
				s1[y] = x
			else:
				s[x] = y
				s1[y] = x
		x = list(set2.difference(set1))
		finish = x[0]
		pred = start
		pred1 = finish
		for i in range(1, n, 2):
			if i == 1:
				a[i] = start
			else:
				a[i] = s[pred]
				pred = a[i]
		if n % 2 == 0:
			n -= 2
		else:
			n -= 1
		for j in range(n, -1, -2):
			if j == n:
				a[j] = finish
			else:
				a[j] = s1[pred1]
				pred1 = a[j]
		print(*a)
	else:
		s = {}
		s1 = {}
		a = [0] * n
		start = 0
		finish = 0
		for i in range(n):
			(x, y) = map(int, input().split())
			if x == 0:
				start = y
				s[x] = y
				s1[y] = x
			elif y == 0:
				finish = x
				s[x] = y
				s1[y] = x
			else:
				s[x] = y
				s1[y] = x
		pred = start
		pred1 = finish
		for i in range(1, n, 2):
			if i == 1:
				a[i] = start
			else:
				a[i] = s[pred]
				pred = a[i]
		if n % 2 == 0:
			n -= 2
		else:
			n -= 1
		for j in range(n, -1, -2):
			if j == n:
				a[j] = finish
			else:
				a[j] = s1[pred1]
				pred1 = a[j]
		print(*a)
main()


n = int(input())
st = {}
fn = {}
for i in range(n):
	(a, b) = input().split()
	st[a] = b
	fn[b] = a
p = [None] * n
z = '0'
for i in range(1, n, 2):
	p[i] = st[z]
	z = st[z]
if n % 2 == 1:
	n += 1
	for u in fn:
		if u not in st:
			fn['0'] = u
			break
z = '0'
for i in range(n - 2, -1, -2):
	p[i] = fn[z]
	z = fn[z]
print(' '.join(p))


def solve(xs):
	starts = list({x[0] for x in xs}.difference({x[1] for x in xs}))
	map_next = {x[0]: x[1] for x in xs}
	ret = starts[:]
	starts = [0] + starts
	for _ in range(len(xs) - 1):
		starts[0] = map_next[starts[0]]
		ret.append(starts[0])
		starts.reverse()
	return ret
xs = [list(map(int, input().split())) for i in range(int(input()))]
print(' '.join(map(str, solve(xs))))


from __future__ import print_function
from collections import *
from sys import stdin
from bisect import *
from heapq import *
from math import *
g = lambda : stdin.readline().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
rr = lambda x: reversed(range(x))
mod = int(1000000000.0) + 7
inf = float('inf')
(n,) = gil()
ans = [None] * n
(left, right) = ({}, {})
nodes = set()
(start, end) = (None, None)
for _ in range(n):
	(x, y) = gil()
	if x:
		nodes.add(x)
	if y:
		nodes.add(y)
	if x == 0:
		start = y
	elif y == 0:
		end = x
	else:
		right[x] = y
		left[y] = x
idx = 1
while idx < n:
	ans[idx] = start
	start = right.get(start, None)
	idx += 2
idx = n - 2
if n & 1:
	idx += 1
	for node in nodes:
		if node != end and node not in right:
			end = node
			break
while idx >= 0 and end:
	ans[idx] = end
	end = left.get(end, None)
	idx -= 2
print(*ans)


n = int(input())
after = {}
prev = {}
for i in range(n):
	(a, b) = [int(i) for i in input().split()]
	after[a] = b
	prev[b] = a
for i in after.keys():
	try:
		prev[i]
	except:
		first = i
		break
second = after[0]
l = [first, second]
for i in range(2, n):
	l.append(after[l[i - 2]])
print(' '.join((str(i) for i in l)))


import bisect
n = int(input())
pairs = [list(map(int, input().split())) for _ in range(n)]
front_set = set()
rear_set = set()
for pair in pairs:
	front_set.add(pair[0])
	rear_set.add(pair[1])
students = [-1] * n
pairs.sort()
fronts = [pair[0] for pair in pairs]
rears = [pair[1] for pair in pairs]
pos = 0
students[pos + 1] = rears[pos]
pos += 2
while pos + 1 < len(pairs):
	i = bisect.bisect_left(fronts, students[pos - 1])
	students[pos + 1] = rears[i]
	pos += 2
students[0] = [i for i in front_set - rear_set][0]
pos = 1
while pos + 1 < len(pairs):
	i = bisect.bisect_left(fronts, students[pos - 1])
	students[pos + 1] = rears[i]
	pos += 2
print(' '.join(map(str, students)))


n = int(input())
d = {}
for i in range(n):
	(a, b) = map(int, input().split())
	d[a] = [a, b]

def ch(po):
	if d.get(po, []) == []:
		return
	while True:
		t = d[po][-1]
		if t == 0 or d.get(t, []) == []:
			break
		d[po] += d[t][1:]
		del d[t]
for x in list(d):
	ch(x)
d[0].pop(0)
t = sum(d.keys())
ans = [d[t][i // 2] if i % 2 == 0 else d[0][i // 2] for i in range(n)]
print(' '.join(map(str, ans)))


n = int(input())
(a, b) = ([0] * 1000001, [0] * 1000001)
hs = [0] * 1000001
for i in range(n):
	(a[i], b[i]) = map(int, input().split(' '))
	hs[a[i]] += 1
	hs[b[i]] += 1
pr = 0
np = 0
for i in range(1000001):
	if hs[i] == 1:
		pr = np
		np = i
hs = [0] * 1000001
for i in range(n):
	hs[a[i]] = b[i]
li = []
if pr in a:
	li.append(pr)
else:
	li.append(np)
for i in range(n):
	if a[i] == 0:
		li.append(b[i])
		break
l = 2
pr = li[0]
nx = li[1]
while l != n:
	li.append(hs[pr])
	(pr, nx) = (nx, hs[pr])
	l += 1
li = [str(i) for i in li]
print(' '.join(li))


n = int(input())
twoback = {}
twofront = {}
for i in range(n):
	(front, back) = [int(x) for x in input().split(' ')]
	twoback[front] = back
	if not back in twoback:
		twoback[back] = -1
	twofront[back] = front
if n % 2 == 0:
	outevens = []
	outodds = []
	fromleft = 0
	fromright = 0
	for i in range(int(n / 2)):
		outevens.append(twoback[fromleft])
		fromleft = outevens[-1]
		outodds.append(twofront[fromright])
		fromright = outodds[-1]
	tosendout = ''
	for (c, d) in zip(outevens, reversed(outodds)):
		tosendout += str(d) + ' ' + str(c) + ' '
	print(tosendout.rstrip(' '))
else:
	fromleft = 0
	for (key, value) in twoback.items():
		if value == -1:
			fromright = key
			break
	outevens = []
	outodds = [fromright]
	for i in range(int(n / 2)):
		outevens.append(twoback[fromleft])
		fromleft = outevens[-1]
		outodds.append(twofront[fromright])
		fromright = outodds[-1]
	for (c, d) in zip(outevens, reversed(outodds)):
		print(d, c, end=' ')
	print(outodds[0])


from operator import itemgetter
from bisect import bisect_left
__author__ = 'artyom'
n = int(input())

def binary_search(a, x):
	pos = bisect_left(a, x, 0, n)
	return pos if pos != n and a[pos] == x else -1
notes = [list(map(int, input().split())) for _ in range(n)]
by_first = sorted(notes, key=itemgetter(0))
by_first_keys = [r[0] for r in by_first]
by_second = sorted(notes, key=itemgetter(1))
by_second_keys = [r[1] for r in by_second]
queue = [by_first[0], next(((x, y) for (x, y) in notes if binary_search(by_second_keys, x) == -1))]
for i in range(0, n - 2):
	queue.append(by_first[bisect_left(by_first_keys, queue[i][1], 0, n)])
restored = [r[0] for r in queue[1:]] + [queue[-2][1]]
print(' '.join(map(str, restored)))


n = int(input())
dic = {}
for i in range(n):
	(a, b) = [int(j) for j in input().split(' ')]
	dic[a] = b
ans = []
ans.append(0)
val = set(dic.values())
for key in dic.keys():
	if key not in val:
		ans.append(key)
		break
for i in range(n - 1):
	ans.append(dic[ans[-2]])
ans = [str(i) for i in ans]
print(' '.join(ans[1:]))


n = int(input())
a = []
ab = 1000002 * [-1]
b = 1000002 * [0]
res = [0, 0]
for i in range(n):
	[aa, bb] = [int(i) for i in input().split()]
	a.append(aa)
	ab[aa] = bb
	b[bb] = 1
	if aa == 0:
		res[1] = bb
for i in a:
	if b[i] == 0:
		res[0] = i
for i in range(2, n):
	res.append(ab[res[i - 2]])
print(*res, sep=' ')


n = int(input())
a = {}
b = {}
ans = [0] * n
s = set()
for i in range(n):
	(x, y) = list(map(int, input().split()))
	a[x] = y
	b[y] = x
	s.add(x)
	s.add(y)
cur = a[0]
for i in range(1, n, 2):
	ans[i] = cur
	if cur in a:
		cur = a[cur]
frst = -1
for i in s:
	if i not in b:
		frst = i
		break
cur = frst
i = 0
for i in range(0, n, 2):
	ans[i] = cur
	if cur in a:
		cur = a[cur]
print(*ans)


n = int(input())
a = [0 for i in range(1000001)]
b = [0 for i in range(1000001)]
times = [0 for i in range(1000001)]
number = [0 for i in range(n)]
for i in range(n):
	(ai, bi) = input().split()
	ai = int(ai)
	bi = int(bi)
	a[ai] = bi
	times[ai] += 1
	times[bi] += 1
	number[i] = ai
	if ai == 0:
		second = bi
for i in range(n):
	if times[number[i]] == 1:
		first = number[i]
		break
a1 = first
a2 = second
print('%d %d' % (a1, a2), end='')
if n % 2 == 0:
	for i in range(n // 2 - 1):
		a1 = a[a1]
		a2 = a[a2]
		print(' %d %d' % (a1, a2), end='')
else:
	for i in range(n // 2 - 1):
		a1 = a[a1]
		a2 = a[a2]
		print(' %d %d' % (a1, a2), end='')
	print(' %d' % a[a1])
print('')


import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import *
from io import BytesIO, IOBase

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def value():
	return tuple(map(int, input().split()))

def array():
	return [int(i) for i in input().split()]

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]
n = Int()
behind = {}
front = {}
numbers = set()
for i in range(n):
	(a, b) = value()
	behind[a] = b
	front[b] = a
	numbers.add(a)
	numbers.add(b)
for i in numbers:
	if i not in front:
		first = i
queue = [0, first]
first = 0
while behind[queue[first]] != 0:
	queue.append(behind[queue[first]])
	first += 1
print(*queue[1:])


import sys
input = sys.stdin.buffer.readline
n = int(input())
ord = [0] * n
next = {}
prev = {}
neighbors = [list(map(int, input().split())) for i in range(n)]
for i in range(n):
	(a, b) = neighbors[i]
	next[a] = b
	prev[b] = a
loc = 1
curr = next[0]
while True:
	ord[loc] = curr
	if curr in next and next[curr] != 0:
		loc += 2
		curr = next[curr]
	else:
		break
if n % 2 == 0:
	loc = n - 2
	curr = prev[0]
else:
	occur_once = []
	for i in range(n):
		for j in neighbors[i]:
			if not (j in next and j in prev):
				occur_once.append(j)
	if occur_once[0] in next:
		occur_once.pop(0)
	else:
		occur_once.pop(1)
	loc = n - 1
	curr = occur_once[0]
while True:
	ord[loc] = curr
	if curr in prev and prev[curr] != 0:
		loc -= 2
		curr = prev[curr]
	else:
		break
print(*ord)


n = int(input())
queue = []
dist = [0] * 1000001
dist2 = [0] * 1000001
dictx = {}
dictx2 = {}
for i in range(n):
	(a, b) = map(int, input().split(' '))
	dictx[a] = b
	dictx2[b] = a
	dist[a] += 1
	dist[b] += 1
	dist2.append(a)
	dist2.append(b)
if n % 2 == 0:
	indx = 0
	final = [0] * n
	curr = 0
	while curr in dictx:
		curr = dictx[curr]
		final[2 * indx + 1] = str(curr)
		indx += 1
	indx = -1
	curr = 0
	while curr in dictx2:
		curr = dictx2[curr]
		final[2 * indx] = str(curr)
		indx -= 1
	print(' '.join(final))
if n % 2 == 1:
	yes = False
	maf = []
	for i in dist2:
		if dist[i] == 1:
			maf.append(i)
	if maf[0] in dictx.keys():
		frontmaf = maf[0]
	else:
		frontmaf = maf[1]
	indx = 0
	final = [0] * n
	curr = frontmaf
	while curr in dictx:
		final[2 * indx] = str(curr)
		curr = dictx[curr]
		indx += 1
	final[2 * indx] = str(curr)
	indx = 0
	curr = 0
	while curr in dictx and dictx[curr] != 0:
		curr = dictx[curr]
		final[2 * indx + 1] = str(curr)
		indx += 1
	print(' '.join(final))


n = int(input())
find_left = {}
find_right = {}
for i in range(n):
	(a, b) = map(int, input().split())
	find_left[a] = b
	find_right[b] = a
f_ele = 0
for key in find_left:
	if key not in find_right:
		f_ele = key
		break
s_ele = find_left[0]
ans = [0] * n
ans[0] = f_ele
ans[1] = s_ele
for i in range(2, n):
	ans[i] = find_left[ans[i - 2]]
for val in ans:
	print(val, end=' ')


import os
maxn = 1000010
(pre, next, ans, vis) = ([], [], [], [])
for i in range(maxn):
	pre.append(-1)
	next.append(-1)
	ans.append(-1)
	vis.append(0)
n = int(input())
for i in range(n):
	(a, b) = input().split()
	(x, y) = (int(a), int(b))
	vis[x] = vis[y] = 1
	pre[y] = x
	next[x] = y
ans[0] = 0
vis[0] = 2
i = 0
j = 2
while next[i] != -1:
	i = next[i]
	if vis[i] == 2:
		break
	ans[j] = i
	j += 2
	vis[i] = 2
j = -1
for i in range(maxn):
	if vis[i] == 1:
		j = i
		break
while pre[j] != -1:
	j = pre[j]
i = j
j = 3
vis[i] = 2
ans[1] = i
while next[i] != -1:
	i = next[i]
	ans[j] = i
	j += 2
	vis[i] = 2
for i in range(n + 2):
	if ans[i] > 0:
		print(ans[i], end=' ')