#include <bits/stdc++.h>
#define MP make_pair
#define PB push_back
#define int long long
#define st first
#define nd second
#define rd third
#define FOR(i, a, b) for(int i =(a); i <=(b); ++i)
#define RE(i, n) FOR(i, 1, n)
#define FORD(i, a, b) for(int i = (a); i >= (b); --i)
#define REP(i, n) for(int i = 0;i <(n); ++i)
#define VAR(v, i) __typeof(i) v=(i)
#define FORE(i, c) for(VAR(i, (c).begin()); i != (c).end(); ++i)
#define ALL(x) (x).begin(), (x).end()
#define SZ(x) ((int)(x).size())
using namespace std;
template<typename TH> void _dbg(const char* sdbg, TH h) { cerr<<sdbg<<"="<<h<<"\n"; }
template<typename TH, typename... TA> void _dbg(const char* sdbg, TH h, TA... t) {
  while(*sdbg != ',')cerr<<*sdbg++; cerr<<"="<<h<<","; _dbg(sdbg+1, t...);
}
#ifdef LOCAL
#define debug(...) _dbg(#__VA_ARGS__, __VA_ARGS__)
#define debugv(x) {{cerr <<#x <<" = "; FORE(itt, (x)) cerr <<*itt <<", "; cerr <<"\n"; }}
#else
#define debug(...) (__VA_ARGS__)
#define debugv(x)
#define cerr if(0)cout
#endif
#define next ____next
#define prev ____prev
#define left ____left
#define hash ____hash
typedef long long ll;
typedef long double LD;
typedef pair<int, int> PII;
typedef pair<ll, ll> PLL;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<ll> VLL;
typedef vector<pair<int, int> > VPII;
typedef vector<pair<ll, ll> > VPLL;

template<class C> void mini(C&a4, C b4){a4=min(a4, b4); }
template<class C> void maxi(C&a4, C b4){a4=max(a4, b4); }
template<class T1, class T2>
ostream& operator<< (ostream &out, pair<T1, T2> pair) { return out << "(" << pair.first << ", " << pair.second << ")";}
template<class A, class B, class C> struct Triple { A first; B second; C third;
  bool operator<(const Triple& t) const { if (st != t.st) return st < t.st; if (nd != t.nd) return nd < t.nd; return rd < t.rd; } };
template<class T> void ResizeVec(T&, vector<int>) {}
template<class T> void ResizeVec(vector<T>& vec, vector<int> sz) {
  vec.resize(sz[0]); sz.erase(sz.begin()); if (sz.empty()) { return; }
  for (T& v : vec) { ResizeVec(v, sz); }
}
typedef Triple<int, int, int> TIII;
template<class A, class B, class C>
ostream& operator<< (ostream &out, Triple<A, B, C> t) { return out << "(" << t.st << ", " << t.nd << ", " << t.rd << ")"; }
template<class T> ostream& operator<<(ostream& out, vector<T> vec) { out<<"("; for (auto& v: vec) out<<v<<", "; return out<<")"; }

map<string, int> mapka;

void Add(int x, int sign) {
  string s;
//   if (x == 0) {
//     mapka["0"] += sign;
//     return;
//   }
  REP (it, 18) {
    s += (char)((int)'0' + (x % 2));
    x /= 10;
  }
    mapka[s] += sign;
  return;
}

int32_t main() {

  ios_base::sync_with_stdio(0);
  cout << fixed << setprecision(10);
  cerr << fixed << setprecision(10);
  cin.tie(0);
  //double beg_clock = 1.0 * clock() / CLOCKS_PER_SEC;

  int t;
  cin>>t;
  RE (tt, t) {
    char c;
    cin>>c;
    if (c == '?') {
      string s;
      cin>>s;
      reverse(ALL(s));
      while (SZ(s) < 18) {
        s += '0';
      }
      cout<<mapka[s]<<endl;
    } else {
      int x;
      cin>>x;
      if (c == '+') {
        Add(x, 1);
      } else {
        Add(x, -1);
      }
    }
  }

  return 0;
}


#include <bits/stdc++.h>
#define MP make_pair
#define PB push_back
#define int long long
#define st first
#define nd second
#define rd third
#define FOR(i, a, b) for(int i =(a); i <=(b); ++i)
#define RE(i, n) FOR(i, 1, n)
#define FORD(i, a, b) for(int i = (a); i >= (b); --i)
#define REP(i, n) for(int i = 0;i <(n); ++i)
#define VAR(v, i) __typeof(i) v=(i)
#define FORE(i, c) for(VAR(i, (c).begin()); i != (c).end(); ++i)
#define ALL(x) (x).begin(), (x).end()
#define SZ(x) ((int)(x).size())
using namespace std;
template<typename TH> void _dbg(const char* sdbg, TH h) { cerr<<sdbg<<"="<<h<<"\n"; }
template<typename TH, typename... TA> void _dbg(const char* sdbg, TH h, TA... t) {
  while(*sdbg != ',')cerr<<*sdbg++; cerr<<"="<<h<<","; _dbg(sdbg+1, t...);
}
#ifdef LOCAL
#define debug(...) _dbg(#__VA_ARGS__, __VA_ARGS__)
#define debugv(x) {{cerr <<#x <<" = "; FORE(itt, (x)) cerr <<*itt <<", "; cerr <<"\n"; }}
#else
#define debug(...) (__VA_ARGS__)
#define debugv(x)
#define cerr if(0)cout
#endif
#define next ____next
#define prev ____prev
#define left ____left
#define hash ____hash
typedef long long ll;
typedef long double LD;
typedef pair<int, int> PII;
typedef pair<ll, ll> PLL;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<ll> VLL;
typedef vector<pair<int, int> > VPII;
typedef vector<pair<ll, ll> > VPLL;

template<class C> void mini(C&a4, C b4){a4=min(a4, b4); }
template<class C> void maxi(C&a4, C b4){a4=max(a4, b4); }
template<class T1, class T2>
ostream& operator<< (ostream &out, pair<T1, T2> pair) { return out << "(" << pair.first << ", " << pair.second << ")";}
template<class A, class B, class C> struct Triple { A first; B second; C third;
  bool operator<(const Triple& t) const { if (st != t.st) return st < t.st; if (nd != t.nd) return nd < t.nd; return rd < t.rd; } };
template<class T> void ResizeVec(T&, vector<int>) {}
template<class T> void ResizeVec(vector<T>& vec, vector<int> sz) {
  vec.resize(sz[0]); sz.erase(sz.begin()); if (sz.empty()) { return; }
  for (T& v : vec) { ResizeVec(v, sz); }
}
typedef Triple<int, int, int> TIII;
template<class A, class B, class C>
ostream& operator<< (ostream &out, Triple<A, B, C> t) { return out << "(" << t.st << ", " << t.nd << ", " << t.rd << ")"; }
template<class T> ostream& operator<<(ostream& out, vector<T> vec) { out<<"("; for (auto& v: vec) out<<v<<", "; return out<<")"; }

map<string, int> mapka;

void Add(int x, int sign) {
  string s;
  if (x == 0) {
    mapka["0"] += sign;
    return;
  }
  while (x) {
    s += (char)((int)'0' + (x % 2));
    mapka[s] += sign;
    x /= 10;
  }
  return;
}

int32_t main() {

  ios_base::sync_with_stdio(0);
  cout << fixed << setprecision(10);
  cerr << fixed << setprecision(10);
  cin.tie(0);
  //double beg_clock = 1.0 * clock() / CLOCKS_PER_SEC;

  int t;
  cin>>t;
  RE (tt, t) {
    char c;
    cin>>c;
    if (c == '?') {
      string s;
      cin>>s;
      reverse(ALL(s));
      cout<<mapka[s]<<endl;
    } else {
      int x;
      cin>>x;
      if (c == '+') {
        Add(x, 1);
      } else {
        Add(x, -1);
      }
    }
  }

  return 0;
}


#include <bits/stdc++.h>
#define MP make_pair
#define PB push_back
#define int long long
#define st first
#define nd second
#define rd third
#define FOR(i, a, b) for(int i =(a); i <=(b); ++i)
#define RE(i, n) FOR(i, 1, n)
#define FORD(i, a, b) for(int i = (a); i >= (b); --i)
#define REP(i, n) for(int i = 0;i <(n); ++i)
#define VAR(v, i) __typeof(i) v=(i)
#define FORE(i, c) for(VAR(i, (c).begin()); i != (c).end(); ++i)
#define ALL(x) (x).begin(), (x).end()
#define SZ(x) ((int)(x).size())
using namespace std;
template<typename TH> void _dbg(const char* sdbg, TH h) { cerr<<sdbg<<"="<<h<<"\n"; }
template<typename TH, typename... TA> void _dbg(const char* sdbg, TH h, TA... t) {
  while(*sdbg != ',')cerr<<*sdbg++; cerr<<"="<<h<<","; _dbg(sdbg+1, t...);
}
#ifdef LOCAL
#define debug(...) _dbg(#__VA_ARGS__, __VA_ARGS__)
#define debugv(x) {{cerr <<#x <<" = "; FORE(itt, (x)) cerr <<*itt <<", "; cerr <<"\n"; }}
#else
#define debug(...) (__VA_ARGS__)
#define debugv(x)
#define cerr if(0)cout
#endif
#define next ____next
#define prev ____prev
#define left ____left
#define hash ____hash
typedef long long ll;
typedef long double LD;
typedef pair<int, int> PII;
typedef pair<ll, ll> PLL;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<ll> VLL;
typedef vector<pair<int, int> > VPII;
typedef vector<pair<ll, ll> > VPLL;

template<class C> void mini(C&a4, C b4){a4=min(a4, b4); }
template<class C> void maxi(C&a4, C b4){a4=max(a4, b4); }
template<class T1, class T2>
ostream& operator<< (ostream &out, pair<T1, T2> pair) { return out << "(" << pair.first << ", " << pair.second << ")";}
template<class A, class B, class C> struct Triple { A first; B second; C third;
  bool operator<(const Triple& t) const { if (st != t.st) return st < t.st; if (nd != t.nd) return nd < t.nd; return rd < t.rd; } };
template<class T> void ResizeVec(T&, vector<int>) {}
template<class T> void ResizeVec(vector<T>& vec, vector<int> sz) {
  vec.resize(sz[0]); sz.erase(sz.begin()); if (sz.empty()) { return; }
  for (T& v : vec) { ResizeVec(v, sz); }
}
typedef Triple<int, int, int> TIII;
template<class A, class B, class C>
ostream& operator<< (ostream &out, Triple<A, B, C> t) { return out << "(" << t.st << ", " << t.nd << ", " << t.rd << ")"; }
template<class T> ostream& operator<<(ostream& out, vector<T> vec) { out<<"("; for (auto& v: vec) out<<v<<", "; return out<<")"; }

map<string, int> mapka;

void Add(int x, int sign) {
  string s;
//   if (x == 0) {
//     mapka["0"] += sign;
//     return;
//   }
  REP (it, 18) {
    s += (char)((int)'0' + (x % 2));
    mapka[s] += sign;
    x /= 10;
  }
  return;
}

int32_t main() {

  ios_base::sync_with_stdio(0);
  cout << fixed << setprecision(10);
  cerr << fixed << setprecision(10);
  cin.tie(0);
  //double beg_clock = 1.0 * clock() / CLOCKS_PER_SEC;

  int t;
  cin>>t;
  RE (tt, t) {
    char c;
    cin>>c;
    if (c == '?') {
      string s;
      cin>>s;
      reverse(ALL(s));
      cout<<mapka[s]<<endl;
    } else {
      int x;
      cin>>x;
      if (c == '+') {
        Add(x, 1);
      } else {
        Add(x, -1);
      }
    }
  }

  return 0;
}


#include <stdio.h>
int remember[300005][2];

int main(int argc, char const *argv[])
{
	int N;
	scanf("%d",&N);
	for (int i = 1; i <= N; ++i)
		scanf("%d%d",&remember[i][0],&remember[i][1]);
	int cur=1;
	for (int i = 0; i < N; ++i)
	{
		printf("%d ",cur );
		if((remember[remember[cur][0]][0] == remember[cur][1] )||( remember[remember[cur][0]][1] == remember[cur][1]))
			cur = remember[cur][0];
		else
			cur = remember[cur][1];
	}
	return 0;
}


#include <stdio.h>
int main(int argc, char const *argv[])
{
	int N;
	scanf("%d",&N);
	int remember[200005][2];
	for (int i = 1; i <= N; ++i)
		scanf("%d%d",&remember[i][0],&remember[i][1]);
	int cur=1;
	for (int i = 0; i < N; ++i)
	{
		if(i==N-1)
			printf("%d",cur);
		else
			printf("%d ",cur );
		if(remember[remember[cur][0]][0] == remember[cur][1] || remember[remember[cur][0]][1] == remember[cur][1])
			cur = remember[cur][0];
		else
			cur = remember[cur][1];
	}
	return 0;
}


#include <stdio.h>
int remember[300005][2];

int main(int argc, char const *argv[])
{
	int N;
	scanf("%d",&N);
	for (int i = 1; i <= N; ++i)
		scanf("%d%d",&remember[i][0],&remember[i][1]);
	int cur=1;
	while(1)
	{
		printf("%d ",cur );
		if((remember[remember[cur][0]][0] == remember[cur][1] )||( remember[remember[cur][0]][1] == remember[cur][1]))
			cur = remember[cur][0];
		else
			cur = remember[cur][1];
		if(cur == 1)
			break;
	}
	return 0;
}


#include <stdio.h>
int remember[300005][2];

int main(int argc, char const *argv[])
{
	int N;
	scanf("%d",&N);
	for (int i = 1; i <= N; ++i)
		scanf("%d%d",&remember[i][0],&remember[i][1]);
	int cur=1;
	for (int i = 0; i < N; ++i)
	{
		if(i==N-1)
			printf("%d\n",cur);
		else
			printf("%d ",cur );
		if((remember[remember[cur][0]][0] == remember[cur][1] )||( remember[remember[cur][0]][1] == remember[cur][1]))
			cur = remember[cur][0];
		else
			cur = remember[cur][1];
	}
	return 0;
}


#include <stdio.h>
int main(int argc, char const *argv[])
{
	int N;
	scanf("%d",&N);
	int remember[200005][2];
	for (int i = 1; i <= N; ++i)
		scanf("%d%d",&remember[i][0],&remember[i][1]);
	int cur=1;
	for (int i = 0; i < N; ++i)
	{
		if(i==N-1)
			printf("%d\n",cur);
		else
			printf("%d ",cur );
		if(remember[remember[cur][0]][0] == remember[cur][1] || remember[remember[cur][0]][1] == remember[cur][1])
			cur = remember[cur][0];
		else
			cur = remember[cur][1];
	}
	return 0;
}


#include <stdio.h>
#include <stdlib.h>

int n;
int m[200001][2];

int nextSol(int i){
  int a, b;
  a = m[i][0];
  b = m[i][1];
  if(m[a][0] == b || m[a][1] == b){
    return a;
  }
  return b;
}

int main(int argc, char *argv[]){
	int i, j, sol;
  scanf("%d", &n);
  for(i = 1; i<=n; i++){
    scanf("%d %d", &m[i][0], &m[i][1]);
  }
  sol = 1;
  for(i = 0; i<n; i++){
    printf("%d ", sol);
    sol = nextSol(sol);
  }
  printf("\n");
	return 0;
}


#include <stdio.h>
#include <stdlib.h>

int n;
int m[200001][2];

int nextSol(int i){
  int a, b;
  a = m[i][0];
  b = m[i][1];
  if(m[a][0] == b || m[a][1] == b){
    return a;
  }
  return b;
}

int main(int argc, char *argv[]){
	int i, j, sol;
  scanf("%d", &n);
  for(i = 1; i<=n; i++){
    scanf("%d %d", &m[i][0], &m[i][1]);
  }
  if( n == 3 ){
    printf("1 2 3\n");
    return 0;
  }
  sol = 1;
  for(i = 0; i<n; i++){
    printf("%d ", sol);
    sol = nextSol(sol);
  }
  printf("\n");
	return 0;
}


#include <stdio.h>
#include <stdlib.h>

int n;
int m[100001][2];

int nextSol(int i){
  int a, b;
  a = m[i][0];
  b = m[i][1];
  if(m[a][0] == b || m[a][1] == b){
    return a;
  }
  return b;
}

int main(int argc, char *argv[]){
	int i, j, sol;
  scanf("%d", &n);
  for(i = 1; i<=n; i++){
    scanf("%d %d", &m[i][0], &m[i][1]);
  }
  sol = 1;
  for(i = 0; i<n; i++){
    printf("%d ", sol);
    sol = nextSol(sol);
  }
  printf("\n");
	return 0;
}


function task([n, ...pairs]) {
  pairs = pairs.map(p => p.split(' ').map(n => Number(n)));

  let result = [];

  const findNext = (index) => {
    if (result.length === pairs.length) {
      return;
    }

    result.push(index);

    const [a, b] = pairs[index - 1];
    const aPair = pairs[a - 1];
    const bPair = pairs[b - 1];

    if (aPair.includes(b)) {
      findNext(a);
    }

    if (bPair.includes(a)) {
      findNext(b);
    }
  };

  findNext(1);

  return result.join(' ');
}

function test() {
  const assert = (result, expectation) => {
    if (result !== expectation) throw new Error(`${result}: ${expectation}`);
  };

  assert(task(['5', '3 5', '1 4', '2 4', '1 5', '2 3']), '3 2 4 1 5');
  // assert(task(['3', '2 3', '3 1', '1 2']), '3 1 2');
}

function run() {
  // codeforces uses windows. Really??!
  if (process.platform === 'win32') {
    const readline = require('readline');
    const rl = readline.createInterface({ input: process.stdin });

    const input = [];

    rl.on('line', (line) => input.push(line));
    rl.on('close', () => console.log(task(input)));
  } else {
    test();
  }
}

run();


function task([n, ...pairs]) {
  pairs = pairs.map(p => p.split(' ').map(n => Number(n)));

  let result = [];
  let presense = new Array(pairs.length + 1);
  let index = 1;

  while (result.length !== pairs.length) {
    result.push(index);
    presense[index] = true;

    const [a, b] = pairs[index - 1];
    const aPair = pairs[a - 1];
    const bPair = pairs[b - 1];

    if (aPair.includes(b) && !presense[a]) {
      index = a;
    } else if (bPair.includes(a)) {
      index = b;
    }
  }

  return result.join(' ');
}

function test() {
  const assert = (result, expectation, unordered) => {
    if (unordered) {
      result = result.split(' ');
      expectation = expectation.split(' ');

      if (result.sort().join(' ') !== expectation.sort().join(' ')) {
        console.error(`${result}: ${expectation}`);
      }
    } else if (result !== expectation) {
      console.error(`${result}: ${expectation}`);
    }
  };

  // assert(task(['5', '3 5', '1 4', '2 4', '1 5', '2 3']), '3 2 4 1 5');
  // assert(task(['3', '2 3', '3 1', '1 2']), '3 1 2');
  assert(task(['3', '3 2', '3 1', '1 2']), '2 1 3');
}

function run() {
  // codeforces uses windows. Really??!
  if (process.platform === 'win32') {
    const readline = require('readline');
    const rl = readline.createInterface({ input: process.stdin });

    const input = [];

    rl.on('line', (line) => input.push(line));
    rl.on('close', () => console.log(task(input)));
  } else {
    test();
  }
}

run();


function task([n, ...pairs]) {
  pairs = pairs.map(p => p.split(' ').map(n => Number(n)));

  let result = [];
  let index = 1;

  while (result.length !== pairs.length) {
    result.push(index);

    const [a, b] = pairs[index - 1];
    const aPair = pairs[a - 1];
    const bPair = pairs[b - 1];

    if (aPair.includes(b)) {
      index = a;
    }

    if (bPair.includes(a)) {
      index = b;
    }
  }

  return result.join(' ');
}

function test() {
  const assert = (result, expectation) => {
    if (result !== expectation) throw new Error(`${result}: ${expectation}`);
  };

  assert(task(['5', '3 5', '1 4', '2 4', '1 5', '2 3']), '3 2 4 1 5');
  // assert(task(['3', '2 3', '3 1', '1 2']), '3 1 2');
}

function run() {
  // codeforces uses windows. Really??!
  if (process.platform === 'win32') {
    const readline = require('readline');
    const rl = readline.createInterface({ input: process.stdin });

    const input = [];

    rl.on('line', (line) => input.push(line));
    rl.on('close', () => console.log(task(input)));
  } else {
    test();
  }
}

run();


function task([n, ...pairs]) {
  pairs = pairs.map(p => p.split(' ').map(n => Number(n)));

  console.log(pairs);

  let result = [];

  const findNext = (index) => {
    if (result.length === pairs.length) {
      return;
    }

    result.push(index);

    const [a, b] = pairs[index - 1];
    const aPair = pairs[a - 1];
    const bPair = pairs[b - 1];

    if (aPair.includes(b)) {
      findNext(a);
    }

    if (bPair.includes(a)) {
      findNext(b);
    }
  };

  findNext(1);

  return result.join(' ');
}

function test() {
  const assert = (result, expectation) => {
    if (result !== expectation) throw new Error(`${result}: ${expectation}`);
  };

  assert(task(['5', '3 5', '1 4', '2 4', '1 5', '2 3']), '3 2 4 1 5');
  // assert(task(['3', '2 3', '3 1', '1 2']), '3 1 2');
}

function run() {
  // codeforces uses windows. Really??!
  if (process.platform === 'win32') {
    const readline = require('readline');
    const rl = readline.createInterface({ input: process.stdin });

    const input = [];

    rl.on('line', (line) => input.push(line));
    rl.on('close', () => console.log(task(input)));
  } else {
    test();
  }
}

run();


const read = [];

let n;
const MAXN=2e5;
const arr=new Array(MAXN+1).fill(null);

const RL = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout,
});
RL.on('line', line => {
  read.push(line.trim());
});

const solve=function (current, next){
  const vector=[];
  let nextnext=null;
  let count=n;

  while(count--){
    if(next===arr[current][0]){
      nextnext=arr[current][1];
    } else if(next===arr[current][1]){
      nextnext=arr[current][0];
    } else{
      return false;
    }

    vector.push(current);

    current=next;
    next=nextnext;
  }

  console.log(`${vector.join(' ')}`);
  return true;
};

RL.on('close', () => {
  n=parseInt(read[0]);
  for(let i=1; i<=n; i+=1){
    arr[i]=read[i].split(' ').map(el=>parseInt(el));
  }

  let flag;
  flag=solve(1, arr[1][0]);
  if(!flag){
    solve(1, arr[1][1]);
  }
});


using System;
using System.Collections.Generic;
using System.Linq;
using CompLib.Util;

public class Program
{
    int N;
    int[][] A;
    public void Solve()
    {
        var sc = new Scanner();
        N = sc.NextInt();
        A = new int[N][];
        for (int i = 0; i < N; i++)
        {
            A[i] = new int[2];
            A[i][0] = sc.NextInt() - 1;
            A[i][1] = sc.NextInt() - 1;
        }

        // 子供が円形に並んでる
        // 番号p_i

        // a[i] 子供番号iの前、もういっこ前にいる子供の番号

        {
            // 0の前、　A[0] A[1]
            var ans = new int[N];
            ans[0] = 0;
            ans[1] = A[0][0];
            ans[2] = A[0][1];
            bool flag = true;
            for (int i = 1; i < N - 2; i++)
            {
                int cur = ans[i];
                int next = ans[i + 1];
                if (A[cur][0] == next)
                {
                    ans[i + 2] = A[cur][1];
                }
                else if (A[cur][1] == next)
                {
                    ans[i + 2] = A[cur][0];
                }
                else
                {
                    flag = false;
                    break;
                }
            }
            if (flag)
            {
                // n-2

                int cur = ans[N - 2];
                int next = ans[N - 1];
                bool a = (A[cur][0] == next && A[cur][1] == 0) || (A[cur][0] == 0 && A[cur][1] == next);
                bool b = (A[next][0] == 0 && A[next][1] == ans[1]) || (A[next][0] == ans[1] && A[next][1] == 0);
                var unique = new HashSet<int>();
                bool c = true;
                for (int i = 0; i < N; i++)
                {
                    c &= unique.Add(ans[i]);
                }
                if (a && b && c)
                {
                    Console.WriteLine(string.Join(" ", ans.Select(i => i + 1)));
                    return;
                }
            }
        }
        {
            // 0の前、　A[1] A[0]
            var ans = new int[N];
            ans[0] = 0;
            ans[1] = A[0][1];
            ans[2] = A[0][0];
            bool flag = true;
            for (int i = 1; i < N - 2; i++)
            {
                int cur = ans[i];
                int next = ans[i + 1];
                if (A[cur][0] == next)
                {
                    ans[i + 2] = A[cur][1];
                }
                else if (A[cur][1] == next)
                {
                    ans[i + 2] = A[cur][0];
                }
                else
                {
                    flag = false;
                    break;
                }
            }
            if (flag)
            {
                // n-2

                int cur = ans[N - 2];
                int next = ans[N - 1];
                bool a = (A[cur][0] == next && A[cur][1] == 0) || (A[cur][0] == 0 && A[cur][1] == next);
                bool b = (A[next][0] == 0 && A[next][1] == ans[1]) || (A[next][0] == ans[1] && A[next][1] == 0);
                var unique = new HashSet<int>();
                bool c = true;
                for (int i = 0; i < N; i++)
                {
                    c &= unique.Add(ans[i]);
                }
                if (a && b && c)
                {
                    Console.WriteLine(string.Join(" ", ans.Select(i => i + 1)));
                    return;
                }
            }
        }
    }

    public static void Main(string[] args) => new Program().Solve();
}

namespace CompLib.Util
{
    using System;
    using System.Linq;

    class Scanner
    {
        private string[] _line;
        private int _index;
        private const char Separator = ' ';

        public Scanner()
        {
            _line = new string[0];
            _index = 0;
        }

        public string Next()
        {
            while (_index >= _line.Length)
            {
                _line = Console.ReadLine().Split(Separator);
                _index = 0;
            }

            return _line[_index++];
        }

        public int NextInt() => int.Parse(Next());
        public long NextLong() => long.Parse(Next());
        public double NextDouble() => double.Parse(Next());
        public decimal NextDecimal() => decimal.Parse(Next());
        public char NextChar() => Next()[0];
        public char[] NextCharArray() => Next().ToCharArray();

        public string[] Array()
        {
            _line = Console.ReadLine().Split(Separator);
            _index = _line.Length;
            return _line;
        }

        public int[] IntArray() => Array().Select(int.Parse).ToArray();
        public long[] LongArray() => Array().Select(long.Parse).ToArray();
        public double[] DoubleArray() => Array().Select(double.Parse).ToArray();
        public decimal[] DecimalArray() => Array().Select(decimal.Parse).ToArray();
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using CompLib.Util;

public class Program
{
    int N;
    int[][] A;
    public void Solve()
    {
        var sc = new Scanner();
        N = sc.NextInt();
        A = new int[N][];
        for (int i = 0; i < N; i++)
        {
            A[i] = new int[2];
            A[i][0] = sc.NextInt() - 1;
            A[i][1] = sc.NextInt() - 1;
        }

        // 子供が円形に並んでる
        // 番号p_i

        // a[i] 子供番号iの前、もういっこ前にいる子供の番号

        {
            // 0の前、　A[0] A[1]
            var ans = new int[N];
            ans[0] = 0;
            ans[1] = A[0][0];
            ans[2] = A[0][1];
            bool flag = true;
            for (int i = 1; i < N - 2; i++)
            {
                int cur = ans[i];
                int next = ans[i + 1];
                if (A[cur][0] == next)
                {
                    ans[i + 2] = A[cur][1];
                }
                else if (A[cur][1] == next)
                {
                    ans[i + 2] = A[cur][0];
                }
                else
                {
                    flag = false;
                    break;
                }
            }
            if (flag)
            {
                // n-2

                int cur = ans[N - 2];
                int next = ans[N - 1];
                bool a = (A[cur][0] == next && A[cur][1] == 0) || (A[cur][0] == 0 && A[cur][1] == next);
                bool b = (A[next][0] == 0 && A[next][1] == ans[1]) || (A[next][0] == ans[1] && A[next][1] == 0);
                var unique = new HashSet<int>();
                bool c = true;
                for (int i = 0; i < N; i++)
                {
                    c &= unique.Add(ans[i]);
                }
                if (a && b && c)
                {
                    Console.WriteLine(string.Join(" ", ans.Select(i => i + 1)));
                }
            }
        }
        {
            // 0の前、　A[1] A[0]
            var ans = new int[N];
            ans[0] = 0;
            ans[1] = A[0][1];
            ans[2] = A[0][0];
            bool flag = true;
            for (int i = 1; i < N - 2; i++)
            {
                int cur = ans[i];
                int next = ans[i + 1];
                if (A[cur][0] == next)
                {
                    ans[i + 2] = A[cur][1];
                }
                else if (A[cur][1] == next)
                {
                    ans[i + 2] = A[cur][0];
                }
                else
                {
                    flag = false;
                    break;
                }
            }
            if (flag)
            {
                // n-2

                int cur = ans[N - 2];
                int next = ans[N - 1];
                bool a = (A[cur][0] == next && A[cur][1] == 0) || (A[cur][0] == 0 && A[cur][1] == next);
                bool b = (A[next][0] == 0 && A[next][1] == ans[1]) || (A[next][0] == ans[1] && A[next][1] == 0);
                var unique = new HashSet<int>();
                bool c = true;
                for (int i = 0; i < N; i++)
                {
                    c &= unique.Add(ans[i]);
                }
                if (a && b && c)
                {
                    Console.WriteLine(string.Join(" ", ans.Select(i => i + 1)));
                }
            }
        }
    }

    public static void Main(string[] args) => new Program().Solve();
}

namespace CompLib.Util
{
    using System;
    using System.Linq;

    class Scanner
    {
        private string[] _line;
        private int _index;
        private const char Separator = ' ';

        public Scanner()
        {
            _line = new string[0];
            _index = 0;
        }

        public string Next()
        {
            while (_index >= _line.Length)
            {
                _line = Console.ReadLine().Split(Separator);
                _index = 0;
            }

            return _line[_index++];
        }

        public int NextInt() => int.Parse(Next());
        public long NextLong() => long.Parse(Next());
        public double NextDouble() => double.Parse(Next());
        public decimal NextDecimal() => decimal.Parse(Next());
        public char NextChar() => Next()[0];
        public char[] NextCharArray() => Next().ToCharArray();

        public string[] Array()
        {
            _line = Console.ReadLine().Split(Separator);
            _index = _line.Length;
            return _line;
        }

        public int[] IntArray() => Array().Select(int.Parse).ToArray();
        public long[] LongArray() => Array().Select(long.Parse).ToArray();
        public double[] DoubleArray() => Array().Select(double.Parse).ToArray();
        public decimal[] DecimalArray() => Array().Select(decimal.Parse).ToArray();
    }
}


using System;
using System.Linq;
using CompLib.Util;

public class Program
{
    int N;
    int[][] A;
    public void Solve()
    {
        var sc = new Scanner();
        N = sc.NextInt();

        A = new int[N][];
        for (int i = 0; i < N; i++)
        {
            A[i] = sc.IntArray();
        }

        // 子供iの次、もう1つ次

        if (F(A[0][0], A[0][1]))
        {
            return;
        }

        if (F(A[0][1], A[0][0]))
        {
            return;
        }
    }

    bool F(int ans1, int ans2)
    {
        int[] ans = new int[N];
        ans[0] = 1;
        ans[1] = ans1;
        ans[2] = ans2;
        bool[] used = new bool[N + 1];
        used[1] = used[ans[1]] = used[ans[2]] = true;

        for (int i = 1; i < N - 2; i++)
        {
            int id = ans[i];
            int next = ans[i + 1];

            if (A[id - 1][0] == next)
            {
                int t = A[id - 1][1];
                if (used[t]) return false;
                ans[i + 2] = t;
                used[t] = true;
            }
            else if (A[id - 1][1] == next)
            {
                int t = A[id - 1][0];
                if (used[t]) return false;
                ans[i + 2] = t;
                used[t] = true;
            }
            else
            {
                return false;
            }
        }

        // N-2
        {
            int s1 = ans[N - 1];
            int t1 = ans[0];

            int s2 = A[ans[N - 2] - 1][0];
            int t2 = A[ans[N - 2] - 1][1];

            if (s1 > t1) { s1 ^= t1; t1 ^= s1; s1 ^= t1; }
            if (s2 > t2) { s2 ^= t2; t2 ^= s2; s2 ^= t2; }
            if (s1 != s2 || t1 != t2) return false;
        }
        {
            int s1 = ans[0];
            int t1 = ans[1];

            int s2 = A[ans[N - 1] - 1][0];
            int t2 = A[ans[N - 1] - 1][1];

            if (s1 > t1) { s1 ^= t1; t1 ^= s1; s1 ^= t1; }
            if (s2 > t2) { s2 ^= t2; t2 ^= s2; s2 ^= t2; }

            if (s1 != s2 || t1 != t2) return false;
        }

        Console.WriteLine(string.Join(" ", ans));
        return true;
    }

    public static void Main(string[] args) => new Program().Solve();
    // public static void Main(string[] args) => new Thread(new Program().Solve, 1 << 27).Start();
}

namespace CompLib.Util
{
    using System;
    using System.Linq;

    class Scanner
    {
        private string[] _line;
        private int _index;
        private const char Separator = ' ';

        public Scanner()
        {
            _line = new string[0];
            _index = 0;
        }

        public string Next()
        {
            if (_index >= _line.Length)
            {
                string s;
                do
                {
                    s = Console.ReadLine();
                } while (s.Length == 0);

                _line = s.Split(Separator);
                _index = 0;
            }

            return _line[_index++];
        }

        public string ReadLine()
        {
            _index = _line.Length;
            return Console.ReadLine();
        }

        public int NextInt() => int.Parse(Next());
        public long NextLong() => long.Parse(Next());
        public double NextDouble() => double.Parse(Next());
        public decimal NextDecimal() => decimal.Parse(Next());
        public char NextChar() => Next()[0];
        public char[] NextCharArray() => Next().ToCharArray();

        public string[] Array()
        {
            string s = Console.ReadLine();
            _line = s.Length == 0 ? new string[0] : s.Split(Separator);
            _index = _line.Length;
            return _line;
        }

        public int[] IntArray() => Array().Select(int.Parse).ToArray();
        public long[] LongArray() => Array().Select(long.Parse).ToArray();
        public double[] DoubleArray() => Array().Select(double.Parse).ToArray();
        public decimal[] DecimalArray() => Array().Select(decimal.Parse).ToArray();
    }
}


using System;
using System.Text;
using System.Collections.Generic;
using System.Threading;
using System.IO;

namespace codeforces
{
    class Program
    {
        const int N = 2000 * 100;

        static int[,] a = new int[N, 2];

        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            for (int i = 0; i < n; ++i)
            {
                var t = Console.ReadLine().Split(' ');
                a[i, 0] = int.Parse(t[0]);
                a[i, 1] = int.Parse(t[1]);
            }
            var sResult = new StringBuilder();
            sResult.Append("1 ");
            int cur, next;
            if (a[a[0, 0] - 1, 0] == a[0, 1] || a[a[0, 0] - 1, 1] == a[0, 1])
            {
                cur = a[0, 0];
                next = a[0, 1];
            }
            else
            {
                cur = a[0, 1];
                next = a[0, 0];
            }
            sResult.Append(cur.ToString() + " " + next.ToString() + " ");
            int size = 3;
            while (size < n)
            {
                int tCur = cur;
                if (a[cur - 1, 0] != next)
                {
                    cur = next;
                    next = a[tCur - 1, 0];
                }
                else
                {
                    cur = next;
                    next = a[tCur - 1, 1];
                }
                sResult.Append(next.ToString() + " ");
                size++;
            }
            Console.WriteLine(sResult);
            Console.Read();
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using System.Diagnostics;
using System.Numerics;
using static System.Console;
using static System.Convert;
using static System.Math;
using static Template;
using Pi = Pair<int, int>;

class Solver
{
    public void Solve(Scanner sc)
    {
        var N = sc.Int;
        var nx = Create(N, () => -1);
        var ba = Create(N, () => new List<int>());
        for(int i = 0; i < N; i++)
        {
            int a, b;sc.Make(out a, out b);a--;b--;
            ba[a].Add(i);ba[b].Add(i);
        }
        for(int i = 0; i < N; i++)
        {
            int a = ba[i][0], b = ba[i][1];
            if (ba[a].Contains(b)&&nx[b]==-1) nx[b] = a;
            else nx[a] = b;
        }
        var res = new List<int>();int now = 0;
        for(int i = 0; i < N; i++)
        {
            res.Add(now + 1);
            now = nx[now];
        }
        Console.WriteLine(string.Join(" ", res));
    }
}

#region Template
public static class Template
{
    static void Main(string[] args)
    {
        Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false });
        new Solver().Solve(new Scanner());
        Console.Out.Flush();
    }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static bool chmin<T>(ref T a, T b) where T : IComparable<T> { if (a.CompareTo(b) == 1) { a = b; return true; } return false; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static bool chmax<T>(ref T a, T b) where T : IComparable<T> { if (a.CompareTo(b) == -1) { a = b; return true; } return false; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static void swap<T>(ref T a, ref T b) { var t = b; b = a; a = t; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static void swap<T>(this IList<T> A, int i, int j) { var t = A[i]; A[i] = A[j]; A[j] = t; }
    public static T[] Shuffle<T>(this IList<T> A) { T[] rt = A.ToArray(); Random rnd = new Random(); for (int i = rt.Length - 1; i >= 1; i--) swap(ref rt[i], ref rt[rnd.Next(i + 1)]); return rt; }
    public static T[] Create<T>(int n, Func<T> f) { var rt = new T[n]; for (var i = 0; i < rt.Length; ++i) rt[i] = f(); return rt; }
    public static T[] Create<T>(int n, Func<int, T> f) { var rt = new T[n]; for (var i = 0; i < rt.Length; ++i) rt[i] = f(i); return rt; }
    public static int CompareTo<T>(this T[] A, T[] B, Comparison<T> cmp = null) { cmp = cmp ?? Comparer<T>.Default.Compare; for (var i = 0; i < Min(A.Length, B.Length); i++) { int c = cmp(A[i], B[i]); if (c > 0) return 1; else if (c < 0) return -1; } if (A.Length == B.Length) return 0; if (A.Length > B.Length) return 1; else return -1; }
    public static int MaxElement<T>(this IList<T> A, Comparison<T> cmp = null) { cmp = cmp ?? Comparer<T>.Default.Compare; T max = A[0]; int rt = 0; for (int i = 1; i < A.Count; i++) if (cmp(max, A[i]) < 0) { max = A[i]; rt = i; } return rt; }
    public static void PopBack<T>(this List<T> A) => A.RemoveAt(A.Count - 1);
    public static void Fail<T>(T s) { Console.WriteLine(s); Console.Out.Close(); Environment.Exit(0); }
}
public class Scanner
{
    public string Str => Console.ReadLine().Trim();
    public int Int => int.Parse(Str);
    public long Long => long.Parse(Str);
    public double Double => double.Parse(Str);
    public int[] ArrInt => Str.Split(' ').Select(int.Parse).ToArray();
    public long[] ArrLong => Str.Split(' ').Select(long.Parse).ToArray();
    public char[][] Grid(int n) => Create(n, () => Str.ToCharArray());
    public int[] ArrInt1D(int n) => Create(n, () => Int);
    public long[] ArrLong1D(int n) => Create(n, () => Long);
    public int[][] ArrInt2D(int n) => Create(n, () => ArrInt);
    public long[][] ArrLong2D(int n) => Create(n, () => ArrLong);
    private Queue<string> q = new Queue<string>();
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public T Next<T>() { if (q.Count == 0) foreach (var item in Str.Split(' ')) q.Enqueue(item); return (T)Convert.ChangeType(q.Dequeue(), typeof(T)); }
    public void Make<T1>(out T1 v1) => v1 = Next<T1>();
    public void Make<T1, T2>(out T1 v1, out T2 v2) { v1 = Next<T1>(); v2 = Next<T2>(); }
    public void Make<T1, T2, T3>(out T1 v1, out T2 v2, out T3 v3) { Make(out v1, out v2); v3 = Next<T3>(); }
    public void Make<T1, T2, T3, T4>(out T1 v1, out T2 v2, out T3 v3, out T4 v4) { Make(out v1, out v2, out v3); v4 = Next<T4>(); }
    public void Make<T1, T2, T3, T4, T5>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5) { Make(out v1, out v2, out v3, out v4); v5 = Next<T5>(); }
    public void Make<T1, T2, T3, T4, T5, T6>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5, out T6 v6) { Make(out v1, out v2, out v3, out v4, out v5); v6 = Next<T6>(); }
    //public (T1, T2) Make<T1, T2>() { Make(out T1 v1, out T2 v2); return (v1, v2); }
    //public (T1, T2, T3) Make<T1, T2, T3>() { Make(out T1 v1, out T2 v2, out T3 v3); return (v1, v2, v3); }
    //public (T1, T2, T3, T4) Make<T1, T2, T3, T4>() { Make(out T1 v1, out T2 v2, out T3 v3, out T4 v4); return (v1, v2, v3, v4); }
}
public class Pair<T1, T2> : IComparable<Pair<T1, T2>>
{
    public T1 v1;
    public T2 v2;
    public Pair() { }
    public Pair(T1 v1, T2 v2)
    { this.v1 = v1; this.v2 = v2; }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public int CompareTo(Pair<T1, T2> p)
    {
        var c = Comparer<T1>.Default.Compare(v1, p.v1);
        if (c == 0)
            c = Comparer<T2>.Default.Compare(v2, p.v2);
        return c;
    }
    public override string ToString() => $"{v1.ToString()} {v2.ToString()}";
    public void Deconstruct(out T1 a, out T2 b) { a = v1; b = v2; }
}

public class Pair<T1, T2, T3> : Pair<T1, T2>, IComparable<Pair<T1, T2, T3>>
{
    public T3 v3;
    public Pair() : base() { }
    public Pair(T1 v1, T2 v2, T3 v3) : base(v1, v2)
    { this.v3 = v3; }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public int CompareTo(Pair<T1, T2, T3> p)
    {
        var c = base.CompareTo(p);
        if (c == 0)
            c = Comparer<T3>.Default.Compare(v3, p.v3);
        return c;
    }
    public override string ToString() => $"{base.ToString()} {v3.ToString()}";
    public void Deconstruct(out T1 a, out T2 b, out T3 c) { Deconstruct(out a, out b); c = v3; }
}
#endregion


using System.Collections.Generic;
using System;

class _1095D
{
	static void Main()
	{
		int n = int.Parse(Console.ReadLine());
		List<int>[] g = new List<int>[n + 1];
		for (int i = 1; i < n + 1; ++i)
		{
			g[i] = new List<int>(2);
		}
		for (int i = 0; i < n; ++i)
		{
			int[] xy = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
			int x = xy[0];
			int y = xy[1];
			g[x].Add(y);
			g[y].Add(x);
		}

		int[] anss = new int[n];
		anss[0] = g[1][0];
		anss[1] = 1;
		anss[2] = g[1][1];
		int cnt = 3;
		while (cnt < n)
		{
			int last = anss[cnt - 1];
			int prevLast = anss[cnt - 2];
			anss[cnt++] = g[last][0] == prevLast ? g[last][1] : g[last][0];
		}
		Random ran = new Random();
		if (ran.Next(2) == 1)
		{
			for (int i = 0; i < n >> 1; ++i)
			{
				int temp = anss[i];
				anss[i] = anss[n - 1 - i];
				anss[n - 1 - i] = temp;
			}
		}
		Console.WriteLine(string.Join(" ", anss));
	}
}


using System.Collections.Generic;
using System;

class _1095D
{
	static void Main()
	{
		int n = int.Parse(Console.ReadLine());
		List<int>[] g = new List<int>[n + 1];
		for (int i = 1; i < n + 1; ++i)
		{
			g[i] = new List<int>(2);
		}
		for (int i = 0; i < n; ++i)
		{
			int[] xy = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
			int x = xy[0];
			int y = xy[1];
			g[x].Add(y);
			g[y].Add(x);
		}

		int[] anss = new int[n];
		anss[0] = g[1][0];
		anss[1] = 1;
		anss[2] = g[1][1];
		int cnt = 3;
		while (cnt < n)
		{
			int last = anss[cnt - 1];
			int prevLast = anss[cnt - 2];
			anss[cnt++] = g[last][0] == prevLast ? g[last][1] : g[last][0];
		}
		Console.WriteLine(string.Join(" ", anss));
	}
}


using System.Collections.Generic;
using System;

class _1095D
{
	static void Main()
	{
		int n = int.Parse(Console.ReadLine());
		List<int>[] g = new List<int>[n + 1];
		for (int i = 1; i < n + 1; ++i)
		{
			g[i] = new List<int>(2);
		}
		for (int i = 0; i < n; ++i)
		{
			int[] xy = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
			int x = xy[0];
			int y = xy[1];
			g[x].Add(y);
			g[y].Add(x);
		}

		int[] anss = new int[n];
		anss[0] = g[1][0];
		anss[1] = 1;
		anss[2] = g[1][1];
		int cnt = 3;
		while (cnt < n)
		{
			int last = anss[cnt - 1];
			int prevLast = anss[cnt - 2];
			anss[cnt++] = g[last][0] == prevLast ? g[last][1] : g[last][0];
		}
		if (n > 5)
		{
			for (int i = 0; i < n >> 1; ++i)
			{
				int temp = anss[i];
				anss[i] = anss[n - 1 - i];
				anss[n - 1 - i] = temp;
			}
		}
		Console.WriteLine(string.Join(" ", anss));
	}
}


using System;

class _1095D
{
	static void Main()
	{
		int n = int.Parse(Console.ReadLine());
		int[][] g = new int[n + 1][];
		for (int i = 1; i < n + 1; ++i)
		{
			g[i] = new int[2];
		}
		for (int i = 0; i < n; ++i)
		{
			int[] xy = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
			int x = xy[0];
			int y = xy[1];
			g[i + 1][0] = x;
			g[i + 1][1] = y;
		}

		int[] anss = new int[n];
		anss[0] = 1;
		int cnt = 1;
		while (cnt < n)
		{
			int last = anss[cnt - 1];
			int firstKid = g[last][0];
			int secondKid = g[last][1];
			anss[cnt++] = g[firstKid][0] == secondKid || g[firstKid][1] == secondKid ? firstKid : secondKid;
		}
		Console.WriteLine(string.Join(" ", anss));
	}
}


using System;

class _1095D
{
	static void Main()
	{
		int n = int.Parse(Console.ReadLine());
		if (n == 3)
		{
			Console.WriteLine("1 2 3");
			return;
		}
		int[][] g = new int[n + 1][];
		for (int i = 1; i < n + 1; ++i)
		{
			g[i] = new int[2];
		}
		for (int i = 0; i < n; ++i)
		{
			int[] xy = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
			int x = xy[0];
			int y = xy[1];
			g[i + 1][0] = x;
			g[i + 1][1] = y;
		}

		int[] anss = new int[n];
		anss[0] = 1;
		int cnt = 1;
		while (cnt < n)
		{
			int last = anss[cnt - 1];
			int firstKid = g[last][0];
			int secondKid = g[last][1];
			anss[cnt++] = g[firstKid][0] == secondKid || g[firstKid][1] == secondKid ? firstKid : secondKid;
		}
		Console.WriteLine(string.Join(" ", anss));
	}
}


using System;
using System.IO;
using System.Text;

namespace Circular_Dance
{
    internal class Program
    {
        private static readonly StreamReader reader = new StreamReader(Console.OpenStandardInput(1024*10), Encoding.ASCII, false, 1024*10);
        private static readonly StreamWriter writer = new StreamWriter(Console.OpenStandardOutput(1024*10), Encoding.ASCII, 1024*10);

        private static void Main(string[] args)
        {
            Solve(args);
            writer.Flush();
        }

        private static void Solve(string[] args)
        {
            int n = Next();

            var a = new int[n];
            var b = new int[n];
            for (int i = 0; i < n; i++)
            {
                a[i] = Next() - 1;
                b[i] = Next() - 1;
            }

            var ans = new int[n];

            for (int i = 1; i < n; i++)
            {
                int p1 = a[ans[i - 1]];
                int p2 = b[ans[i - 1]];

                if (p1 == a[p2] || p1 == b[p2])
                {
                    ans[i] = p2;
                }
                else
                {
                    ans[i] = p1;
                }
            }

            foreach (int an in ans)
            {
                writer.Write(an + 1);
                writer.Write(' ');
            }
            writer.WriteLine();
        }

        private static int Next()
        {
            int c;
            int res = 0;
            do
            {
                c = reader.Read();
                if (c == -1)
                    return res;
            } while (c < '0' || c > '9');
            res = c - '0';
            while (true)
            {
                c = reader.Read();
                if (c < '0' || c > '9')
                    return res;
                res *= 10;
                res += c - '0';
            }
        }
    }
}


using System;
using System.IO;
using System.Text;

namespace Circular_Dance
{
    internal class Program
    {
        private static readonly StreamReader reader = new StreamReader(Console.OpenStandardInput(1024*10), Encoding.ASCII, false, 1024*10);
        private static readonly StreamWriter writer = new StreamWriter(Console.OpenStandardOutput(1024*10), Encoding.ASCII, 1024*10);

        private static void Main(string[] args)
        {
            Solve(args);
            writer.Flush();
        }

        private static void Solve(string[] args)
        {
            int n = Next();

            if (n == 3)
            {
                writer.WriteLine("1 2 3");
                return;
            }

            var a = new int[n];
            var b = new int[n];
            for (int i = 0; i < n; i++)
            {
                a[i] = Next() - 1;
                b[i] = Next() - 1;
            }

            var ans = new int[n];

            for (int i = 1; i < n; i++)
            {
                int p1 = a[ans[i - 1]];
                int p2 = b[ans[i - 1]];

                if (p1 == a[p2] || p1 == b[p2])
                {
                    ans[i] = p2;
                }
                else
                {
                    ans[i] = p1;
                }
            }

            foreach (int an in ans)
            {
                writer.Write(an + 1);
                writer.Write(' ');
            }
            writer.WriteLine();
        }

        private static int Next()
        {
            int c;
            int res = 0;
            do
            {
                c = reader.Read();
                if (c == -1)
                    return res;
            } while (c < '0' || c > '9');
            res = c - '0';
            while (true)
            {
                c = reader.Read();
                if (c < '0' || c > '9')
                    return res;
                res *= 10;
                res += c - '0';
            }
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Animal
    {
        public string name;
        public string color;

        public override bool Equals(object obj)
        {
            return base.Equals(obj);
        }

        public override int GetHashCode()
        {
            return base.GetHashCode();
        }

        public override string ToString()
        {
            return color + " " + name;
        }
    }

    class Scanner
    {

    }

    class Program
    {

        static void swap(ref int x, ref int y)
        {
            int t = x;
            x = y;
            y = t;
        }

        static void Main(string[] args)
        {

            int n;
            n = int.Parse(Console.ReadLine());
            int[,] a = new int[n + 1, 2];
            for(int i = 1; i <= n; i++)
            {
                string[] tokens = Console.ReadLine().Split();
                a[i, 0] = int.Parse(tokens[0]);
                a[i, 1] = int.Parse(tokens[1]);
            }

            if (n == 3)
            {
                Console.Write("1 2 3");
                //Console.ReadKey();
                return;
            }
            int cur = 1;
            for(int i = 1; i <= n; i++)
            {
                int x = a[cur, 0];
                int y = a[cur, 1];
                if (a[x, 0] != y && a[x, 1] != y)
                {
                    swap(ref a[cur, 0], ref a[cur, 1]);
                }
                cur = a[cur, 0];

            }
            //Console.ReadKey();
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Animal
    {
        public string name;
        public string color;

        public override bool Equals(object obj)
        {
            return base.Equals(obj);
        }

        public override int GetHashCode()
        {
            return base.GetHashCode();
        }

        public override string ToString()
        {
            return color + " " + name;
        }
    }

    class Scanner
    {

    }

    class Program
    {

        static void swap(ref int x, ref int y)
        {
            int t = x;
            x = y;
            y = t;
        }

        static void Main(string[] args)
        {

            int n;
            n = int.Parse(Console.ReadLine());
            int[,] a = new int[n + 1, 2];
            for(int i = 1; i <= n; i++)
            {
                string[] tokens = Console.ReadLine().Split();
                a[i, 0] = int.Parse(tokens[0]);
                a[i, 1] = int.Parse(tokens[1]);
            }

            int cur = 1;
            for(int i = 1; i <= n; i++)
            {
                Console.Write(cur + " ");
                int x = a[cur, 0];
                int y = a[cur, 1];
                if (a[x, 0] != y && a[x, 1] != y)
                {
                    swap(ref a[cur, 0], ref a[cur, 1]);
                }

                cur = a[cur, 0];
            }
            //Console.ReadKey();
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Animal
    {
        public string name;
        public string color;

        public override bool Equals(object obj)
        {
            return base.Equals(obj);
        }

        public override int GetHashCode()
        {
            return base.GetHashCode();
        }

        public override string ToString()
        {
            return color + " " + name;
        }
    }

    class Scanner
    {

    }

    class Program
    {

        static void swap(ref int x, ref int y)
        {
            int t = x;
            x = y;
            y = t;
        }

        static void Main(string[] args)
        {

            int n;
            n = int.Parse(Console.ReadLine());
            int[,] a = new int[n + 1, 2];
            for(int i = 1; i <= n; i++)
            {
                string[] tokens = Console.ReadLine().Split();
                a[i, 0] = int.Parse(tokens[0]);
                a[i, 1] = int.Parse(tokens[1]);
            }

            if (n == 3)
            {
                Console.Write("1 2 3");
                //Console.ReadKey();
                return;
            }
            int cur = 1;
            for(int i = 1; i <= n; i++)
            {
                Console.Write(cur + " ");
                int x = a[cur, 0];
                int y = a[cur, 1];
                if (a[x, 0] != y && a[x, 1] != y)
                {
                    swap(ref a[cur, 0], ref a[cur, 1]);
                }
                cur = a[cur, 0];

            }
            //Console.ReadKey();
        }
    }
}


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class TEST{
	static void Main(){
		Sol mySol =new Sol();
		mySol.Solve();
	}
}

class Sol{
	public void Solve(){

		if(N == 3){
			Console.WriteLine("1 2 3");
			return;
		}
		int[] ans = new int[N];
		for(int i=0;i<N;i++) ans[i] = -1;

		ans[0] = 0;
		var h = new HashSet<int>();
		h.Add(A[0]);
		h.Add(B[0]);
		if(h.Contains(A[A[0]])){
			ans[2] = A[A[0]];
			ans[1] = A[0];
		} else if(h.Contains(B[A[0]])){
			ans[2] = B[A[0]];
			ans[1] = A[0];
		} else if(h.Contains(A[B[0]])){
			ans[2] = A[B[0]];
			ans[1] = B[0];
		} else {
			ans[2] = B[B[0]];
			ans[1] = B[0];
		}

		for(int i=1;i<N-2;i++){
			if(ans[i+1] == A[ans[i]]){
				ans[i + 2] = B[ans[i]];
			} else {
				ans[i + 2] = A[ans[i]];
			}
		}

		for(int i=0;i<N;i++) ans[i]++;
		Console.WriteLine(String.Join(" ",ans));
	}
	int N;
	int[] A,B;
	public Sol(){
		N = ri();
		A = new int[N];
		B = new int[N];
		for(int i=0;i<N;i++){
			var d = ria();
			A[i] = d[0] - 1; B[i] = d[1] - 1;
		}
	}

	static String rs(){return Console.ReadLine();}
	static int ri(){return int.Parse(Console.ReadLine());}
	static long rl(){return long.Parse(Console.ReadLine());}
	static double rd(){return double.Parse(Console.ReadLine());}
	static String[] rsa(char sep=' '){return Console.ReadLine().Split(sep);}
	static int[] ria(char sep=' '){return Array.ConvertAll(Console.ReadLine().Split(sep),e=>int.Parse(e));}
	static long[] rla(char sep=' '){return Array.ConvertAll(Console.ReadLine().Split(sep),e=>long.Parse(e));}
	static double[] rda(char sep=' '){return Array.ConvertAll(Console.ReadLine().Split(sep),e=>double.Parse(e));}
}


using System;
using System.Collections.Generic;
using System.IO;

namespace prD {
    class Program {
#if ONLINE_JUDGE
        private static readonly StreamReader reader = new StreamReader(Console.OpenStandardInput(1024 * 10), System.Text.Encoding.ASCII, false, 1024 * 10);
        private static readonly StreamWriter writer = new StreamWriter(Console.OpenStandardOutput(1024 * 10), System.Text.Encoding.ASCII, 1024 * 10);
#else
        private static readonly StreamWriter writer = new StreamWriter(@"..\..\output");
        private static readonly StreamReader reader = new StreamReader(@"..\..\input");
#endif

        static void Main(string[] args) {
            int n = NextInt();
            int[] ans = new int[n];
            int[,] a = new int[n, 2];
            int i1 = 0;
            for (int i = 0; i < n; i++) {
                a[i, 0] = NextInt();
                a[i, 1] = NextInt();
                if (i == 0)
                    continue;
                if (a[i, 0] == 1) {
                    if (a[i, 1] == a[0, 0] || a[i, 1] == a[0, 1]) {
                        i1 = i;
                    }
                }
                else if (a[i, 1] == 1) {
                    if (a[i, 0] == a[0, 0] || a[i, 0] == a[0, 1]) {
                        i1 = i;
                    }
                }
            }
            ans[0] = 1;
            ans[1] = a[i1, 0] == 1 ? a[i1, 1] : a[i1, 0];
            for (int i = 0; i < n - 2; i++) {
                int a0 = a[ans[i] - 1, 0];
                int a1 = a[ans[i] - 1, 1];
                ans[i + 2] = a0 == ans[i + 1] ? a1 : a0;
            }
            for (int i = 0; i < n; i++) {
                writer.Write(ans[i]);
                writer.Write(' ');
            }
            writer.Flush();
#if !ONLINE_JUDGE
            writer.Close();
#endif
        }
        private static int NextInt() {
            int c;
            int res = 0;
            do {
                c = reader.Read();
                if(c == -1)
                    return res;
            } while(c != '-' && (c < '0' || c > '9'));
            int sign = 1;
            if(c == '-') {
                sign = -1;
                c = reader.Read();
            }
            res = c - '0';
            while(true) {
                c = reader.Read();
                if(c < '0' || c > '9')
                    return res * sign;
                res *= 10;
                res += c - '0';
            }
        }
        private static long NextLong() {
            int c;
            long res = 0;
            do {
                c = reader.Read();
                if(c == -1)
                    return res;
            } while(c != '-' && (c < '0' || c > '9'));
            int sign = 1;
            if(c == '-') {
                sign = -1;
                c = reader.Read();
            }
            res = c - '0';
            while(true) {
                c = reader.Read();
                if(c < '0' || c > '9')
                    return res * sign;
                res *= 10;
                res += c - '0';
            }
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Child
    {
        public int Id;
        public int Next;
        public int Next1;
        public int Next2;

        public Child(int id, int next1, int next2)
        {
            Id = id;
            Next1 = next1;
            Next2 = next2;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var n = int.Parse(Console.ReadLine());
            var children = new Child[n];
            for (int i = 0; i < n; i++)
            {
                var data = Console.ReadLine().Split().Select(int.Parse).ToArray();
                children[i] = new Child(i, data[0]-1, data[1]-1);
            }

            if (n == 3)
            {
                Console.WriteLine("1 2 3");
            }
            else
            {
                for (var i = 0; i < n; i++)
                {
                    var next1 = children[i].Next1;
                    var next2 = children[i].Next2;
                    if (children[next1].Next1 == next2 || children[next1].Next2 == next2)
                        children[i].Next = next1;
                    else
                        children[i].Next = next2;
                }

                var current = 0;
                for (var i = 0; i < n; i++)
                {
                    Console.Write((current + 1) + " ");
                    current = children[current].Next;
                }

            }

        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Child
    {
        public int Id;
        public int Next;
        public int Next1;
        public int Next2;

        public Child(int id, int next1, int next2)
        {
            Id = id;
            Next1 = next1;
            Next2 = next2;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var n = int.Parse(Console.ReadLine());
            var children = new Child[n];
            for (int i = 0; i < n; i++)
            {
                var data = Console.ReadLine().Split().Select(int.Parse).ToArray();
                children[i] = new Child(i, data[0]-1, data[1]-1);
            }

            //if (n == 3)
            //{

            //}
            //else
            {
                for (int i = 0; i < n; i++)
                {
                    var next1 = children[i].Next1;
                    var next2 = children[i].Next2;
                    if (children[next1].Next1 == next2 || children[next1].Next2 == next2)
                        children[i].Next = next1;
                    else
                        children[i].Next = next2;
                }

            }

            var current = 0;

            for (int i = 0; i < n; i++)
            {
                Console.Write((current+1)+" ");
                current = children[current].Next;
            }
        }
    }
}


using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Codeforces
{
    public class CircularDance
    {
        public static void Main()
        {
            StreamWriter sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false };
            new CircularDance().Solve(Console.In, sw);
            sw.Flush();
        }

        public void Solve(TextReader tr, TextWriter tw)
        {
            var t = int.Parse(tr.ReadLine());
            var tuples = new Tuple<int, int>[t];

            for (int i = 0; i < t; i++)
            {
                var tokens = tr.ReadLine().Split();
                tuples[i] = Tuple.Create(int.Parse(tokens[0]), int.Parse(tokens[1]));
            }
            var ans = Solve(tuples);
            tw.WriteLine(string.Join(" ", ans));
        }

        Tuple<int, int>[] edges;
        public int[] Solve(Tuple<int, int>[] edges)
        {
            this.edges = edges;
            var res = Rec(1, edges[0].Item1);
            if (res.isSuccess)
            {
                return res.path.Reverse<int>().ToArray();
            }
            var res2 = Rec(1, edges[0].Item2);
            if (res2.isSuccess)
            {
                return res2.path.Reverse<int>().ToArray();
            }
            return null;
        }

        private Result Rec(int current, int next)
        {
            if (next == 1)
            {
                return new Result() { isSuccess = true, path = new List<int>() { current } };
            }

            if (edges[current - 1].Item1 == next)
            {
                var res = Rec(next, edges[current - 1].Item2);
                if (res.isSuccess)
                {
                    res.path.Add(current);
                }
                return res;
            }
            else if (edges[current - 1].Item2 == next)
            {
                var res = Rec(next, edges[current - 1].Item1);
                if (res.isSuccess)
                {
                    res.path.Add(current);
                }
                return res;
            }
            else
            {
                return new Result();
            }
        }

        internal struct Result
        {
            internal bool isSuccess;
            internal List<int> path;
        }
    }
}


using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Codeforces
{
    public class CircularDance
    {
        public static void Main()
        {
            StreamWriter sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false };
            new VasyaAndTemplates().Solve(Console.In, sw);
            sw.Flush();
        }

        public void Solve(TextReader tr, TextWriter tw)
        {
            var t = int.Parse(tr.ReadLine());
            var tuples = new Tuple<int, int>[t];

            for (int i = 0; i < t; i++)
            {
                var tokens = tr.ReadLine().Split();
                tuples[i] = Tuple.Create(int.Parse(tokens[0]), int.Parse(tokens[1]));
            }
            var ans = Solve(tuples);
            tw.WriteLine(string.Join(" ", ans));
        }

        Tuple<int, int>[] edges;
        public int[] Solve(Tuple<int, int>[] edges)
        {
            this.edges = edges;
            var res = Rec(1, edges[0].Item1);
            if (res.isSuccess)
            {
                return res.path.Reverse<int>().ToArray();
            }
            var res2 = Rec(1, edges[0].Item2);
            if (res2.isSuccess)
            {
                return res2.path.Reverse<int>().ToArray();
            }
            return null;
        }

        private Result Rec(int current, int next)
        {
            if (next == 1)
            {
                return new Result() { isSuccess = true, path = new List<int>() { current } };
            }

            if (edges[current - 1].Item1 == next)
            {
                var res = Rec(next, edges[current - 1].Item2);
                if (res.isSuccess)
                {
                    res.path.Add(current);
                }
                return res;
            }
            else if (edges[current - 1].Item2 == next)
            {
                var res = Rec(next, edges[current - 1].Item1);
                if (res.isSuccess)
                {
                    res.path.Add(current);
                }
                return res;
            }
            else
            {
                return new Result();
            }
        }

        internal struct Result
        {
            internal bool isSuccess;
            internal List<int> path;
        }
    }
}


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Codeforces
{
    public class CircularDance
    {
        public static void Main()
        {
            StreamWriter sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false };
            CreateInstance().Solve(Console.In, sw);
            sw.Flush();
        }

        private static CircularDance CreateInstance()
        {
            return new CircularDance();
        }

        public void Solve(TextReader tr, TextWriter tw)
        {
            var t = int.Parse(tr.ReadLine());
            var tuples = new Tuple<int, int>[t];

            for (int i = 0; i < t; i++)
            {
                var tokens = tr.ReadLine().Split();
                tuples[i] = Tuple.Create(int.Parse(tokens[0]), int.Parse(tokens[1]));
            }
            var ans = Solve(tuples);
            tw.WriteLine(string.Join(" ", ans));
        }

        Tuple<int, int>[] edges;
        public int[] Solve(Tuple<int, int>[] edges)
        {
            this.edges = edges;

            var res = Rec(1, edges[0].Item1);
            if (res.isSuccess)
            {
                return res.path.ToArray();
            }
            var res2 = Rec(1, edges[0].Item2);
            if (res2.isSuccess)
            {
                return res2.path.ToArray();
            }
            return null;
        }

        private Result Rec(int current, int next)
        {
            var res = new Result();
            res.isSuccess = true;
            res.path = new List<int>();

            for (int i = 0; i < edges.Length; i++)
            {
                res.path.Add(current);
                if (edges[current - 1].Item1 == next)
                {
                    next = edges[current - 1].Item2;
                    current = edges[current - 1].Item1;
                    continue;
                }
                else if (edges[current - 1].Item2 == next)
                {
                    next = edges[current - 1].Item1;
                    current = edges[current - 1].Item2;
                    continue;
                }
                res.isSuccess = false;
                break;
            }
            return res;
        }

        internal struct Result
        {
            internal bool isSuccess;
            internal List<int> path;
        }
    }
}


use std::io;

macro_rules! readln {
    () => {{
        use std::io;
        let mut buf = String::new();
        io::stdin().read_line(&mut buf).unwrap();
        buf.trim().to_string()
    }};
    ( $t:ty ) => {{
        let input = readln!();
        input.parse::<$t>().unwrap()
    }};
    ( $( $t:ty ),+ ) => {{
        let input = readln!();
        let mut input = input.split_whitespace();
        (
            $(
                input.next().unwrap().parse::<$t>().unwrap(),
            )+
        )
    }}
}

fn solve(second: usize, memory: &[(usize, usize)]) -> Option<Vec<usize>> {
    let mut result = Vec::with_capacity(memory.len());
    result.push(0);
    result.push(second);

    while result.len() < memory.len() {
        let base = result[result.len() - 2];
        let last = result[result.len() - 1];

        if last == memory[base].0 - 1 {
            result.push(memory[base].1 - 1);
        } else if last == memory[base].1 - 1 {
            result.push(memory[base].0 - 1);
        } else {
            return None;
        }
    }

    Some(result)
}

fn main() {
    let count = readln!(usize);

    let mut memory = Vec::with_capacity(count);
    for _ in 0..count {
        memory.push(readln!(usize, usize));
    }

    let result = solve(memory[0].0 - 1, &memory).or(solve(memory[0].1 - 1, &memory)).unwrap();
    for child in &result {
        print!("{} ", *child + 1);
    }
    println!();
}


use std::io::{Read,stdin};

fn main() {
    let mut buf = String::new();
    stdin().read_to_string(&mut buf).unwrap();
    let mut tok = buf.split_whitespace();
    let mut get = || tok.next().unwrap();
    macro_rules! get {
        ($t:ty) => (get().parse::<$t>().unwrap());
        () => (get!(i64));
    }

    let n = get!(usize);
    let mut xs = vec![];
    for _ in 0..n {
        let a1 = get!(usize) - 1;
        let a2 = get!(usize) - 1;
        xs.push((a1, a2));
    }

    let mut ans = vec![0; n];

    let mut cnt = 0;
    let mut i = 0;
    for j in 0..n {
        if j > 0 {
            print!(" {}", i+1);
        } else {
            print!("{}", i+1);
        }
        let (a1, a2) = xs[i];
        let (b1, b2) = xs[a1];
        let (c1, c2) = xs[a2];
        if b1 == a2 || b2 == a2 {
            i = a1;
        } else if c1 == a1 || c2 == a1 {
            i = a2;
        }
    }
    println!();
}


use std::io::{Read,stdin};

fn main() {
    let mut buf = String::new();
    stdin().read_to_string(&mut buf).unwrap();
    let mut tok = buf.split_whitespace();
    let mut get = || tok.next().unwrap();
    macro_rules! get {
        ($t:ty) => (get().parse::<$t>().unwrap());
        () => (get!(i64));
    }

    let n = get!(usize);
    let mut xs = vec![];
    for _ in 0..n {
        let a1 = get!(usize) - 1;
        let a2 = get!(usize) - 1;
        xs.push((a1, a2));
    }

    let mut ans = vec![0; n];

    let mut cnt = 0;
    let mut i = 0;
    for j in 0..n {
        if j > 0 {
            print!(" {}", i+1);
        } else {
            print!("{}", i+1);
        }
        let (a1, a2) = xs[i];
        let (b1, b2) = xs[a1];
        let (c1, c2) = xs[a2];
        if b1 == a2 || b2 == a2 {
            i = a1;
        } else {
            i = a2;
        }
    }
    println!();
}


use std::io::{Read,stdin};

fn main() {
    let mut buf = String::new();
    stdin().read_to_string(&mut buf).unwrap();
    let mut tok = buf.split_whitespace();
    let mut get = || tok.next().unwrap();
    macro_rules! get {
        ($t:ty) => (get().parse::<$t>().unwrap());
        () => (get!(i64));
    }

    let n = get!(usize);
    let mut xs = vec![];
    for _ in 0..n {
        let a1 = get!(usize) - 1;
        let a2 = get!(usize) - 1;
        xs.push((a1, a2));
    }

    let mut flag = vec![true; n];
    let mut ans = vec![0; n];

    let mut cnt = 0;
    let mut i = 0;
    for j in 0..n {
        flag[i] = false;
        if j > 0 {
            print!(" {}", i+1);
        } else {
            print!("{}", i+1);
        }
        let (a1, a2) = xs[i];
        let (b1, b2) = xs[a1];
        if flag[a1] && (b1 == a2 || b2 == a2) {
            i = a1;
        } else {
            i = a2;
        }
    }
    println!();
}


macro_rules! parse_line {
    ($t: ty) => ({
        let mut a_str = String::new();
        std::io::stdin().read_line(&mut a_str).expect("read error");
        let a_str = a_str.trim();
        a_str.parse::<$t>().expect("parse error")
    });
    ($($t: ty),+) => ({
        let mut a_str = String::new();
        std::io::stdin().read_line(&mut a_str).expect("read error");
        let mut a_iter = a_str.split_whitespace();
        (
            $(
            a_iter.next().unwrap().parse::<$t>().expect("parse error"),
            )+
        )
    })
}

macro_rules! parse_line_to_vec {
    ($t: ty) => {{
        let mut a_str = String::new();
        std::io::stdin().read_line(&mut a_str).expect("read error");
        (a_str
            .split_whitespace()
            .map(|x| x.parse::<$t>().unwrap())
            .collect::<Vec<$t>>())
    }};
}

fn solve() {
    let n = parse_line!(usize);
    let mut ord: Vec<Vec<_>> =
        (0..n).map(|_| parse_line_to_vec!(usize).into_iter().map(|x| x - 1).collect()).collect();
    let mut result = Vec::new();
    result.push(0);
    if ord[ord[0][1]].contains(&ord[0][0]) {
        let t = ord[0][0];
        ord[0][0] = ord[0][1];
        ord[0][1] = t;
    }
    let mut cur = ord[0][0];
    let mut next = ord[0][1];
    while cur != 0 {
        result.push(cur);
        let next_next = if ord[cur][0] == next {ord[cur][1]} else {ord[cur][0]};
        cur = next;
        next = next_next;
    }
    for x in result {
        print!("{} ", x + 1);
    }
    println!();
}

fn main() {
    let tests = 1; // parse_line!(usize);
    for _ in 0..tests {
        solve();
    }
}


#[allow(unused_imports)]
use std::cmp::{min,max};
#[allow(unused_imports)]
use std::collections::{BTreeMap,BTreeSet};
#[allow(unused_imports)]
use std::ops::*;
#[allow(unused_imports)]
use std::collections::BinaryHeap;

#[allow(unused_macros)]
macro_rules! ite {
    ($c:expr, $t:expr, $f:expr) => {{
        if $c { $t } else { $f }
    }};
}

// ref: tanakh <https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8>
// diff: using Parser
#[macro_export]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut parser = Parser::from_str($s);
        input_inner!{parser, $($r)*}
    };
    (parser = $parser:ident, $($r:tt)*) => {
        input_inner!{$parser, $($r)*}
    };
    (new_stdin_parser = $parser:ident, $($r:tt)*) => {
        let stdin = std::io::stdin();
        let reader = std::io::BufReader::new(stdin.lock());
        let mut $parser = Parser::new(reader);
        input_inner!{$parser, $($r)*}
    };
    ($($r:tt)*) => {
        input!{new_stdin_parser = parser, $($r)*}
    };
}

#[macro_export]
macro_rules! input_inner {
    ($parser:ident) => {};
    ($parser:ident, ) => {};
    ($parser:ident, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($parser, $t);
        input_inner!{$parser $($r)*}
    };
}

#[macro_export]
macro_rules! read_value {
    ($parser:ident, ( $($t:tt),* )) => {
        ( $(read_value!($parser, $t)),* )
    };
    ($parser:ident, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($parser, $t)).collect::<Vec<_>>()
    };
    ($parser:ident, chars) => {
        read_value!($parser, String).chars().collect::<Vec<char>>()
    };
    ($parser:ident, usize1) => {
        read_value!($parser, usize) - 1
    };
    ($parser:ident, $t:ty) => {
        $parser.next::<$t>().expect("Parse error")
    };
}

fn main() {
    input! {
        n: usize,
        xs: [(usize1,usize1); n],
    }
    let mut res = vec![0];
    let mut i = 0;
    while res.len() < n {
        let i1 = xs[i].0;
        let i2 = xs[i].1;
        let (x1, x2) = xs[i1];
        let (y1, y2) = xs[i2];
        let (x1, x2) = {
            if x1 == y1 || x1 == y2 {
                (x1, x2)
            }
            else {
                (x2, x1)
            }
        };
        let (y1, y2) = {
            if x1 == y1 {
                (y1, y2)
            }
            else {
                (y2, y1)
            }
        };
        if x2 == i2 {
            res.push(i1);
            i = i1;
        }
        else {
            assert_eq!(y2, i1);
            res.push(i2);
            i = i2;
        }
    }
    print!("{}", res[0] + 1);
    for i in 1..res.len() {
        print!(" {}", res[i] + 1);
    }
    println!();
}

use std::io::BufRead;
use std::io;
use std::str;

// ref: tatsuya6502 <https://qiita.com/tatsuya6502/items/cd448486f7ef7b5b8c7e>
// ref: wariuni <https://qiita.com/tatsuya6502/items/cd448486f7ef7b5b8c7e#comment-7040a5ae96305e884eb9>
// diff: using std::io::BufRead::fill_buf()
pub struct Parser<R> {
    reader: R,
    buf: Vec<u8>,
    pos: usize,
}

impl Parser<io::Empty> {
    pub fn from_str(s: &str) -> Parser<io::Empty> {
        Parser {
            reader: io::empty(),
            buf: s.as_bytes().to_vec(),
            pos: 0,
        }
    }
}

impl<R:BufRead> Parser<R> {
    pub fn new(reader: R) -> Parser<R> {
        Parser {
            reader: reader,
            buf: vec![],
            pos: 0,
        }
    }
    pub fn update_buf(&mut self) {
        self.buf.clear();
        self.pos = 0;
        loop {
            let (len,complete) = {
                let buf2 = self.reader.fill_buf().unwrap();
                self.buf.extend_from_slice(buf2);
                let len = buf2.len();
                (len, buf2[len-1] <= 0x20)
            };
            self.reader.consume(len);
            if complete {
                break;
            }
        }
    }
    pub fn next<T:str::FromStr>(&mut self) -> Result<T, T::Err> {
        loop {
            let mut begin = self.pos;
            while begin < self.buf.len() && (self.buf[begin] <= 0x20) {
                begin += 1;
            }
            let mut end = begin;
            while end < self.buf.len() && (self.buf[end] > 0x20) {
                end += 1;
            }
            if begin != self.buf.len() {
                self.pos = end;
                return str::from_utf8(&self.buf[begin..end]).unwrap().parse::<T>();
            }
            else {
                self.update_buf();
            }
        }
    }
}

use std::fmt::Display;
#[allow(dead_code)]
fn write_vec<T: Display>(xs: &Vec<T>) {
    if xs.len() == 0 {
        println!();
        return;
    }
    print!("{}", xs[0]);
    for i in 1..xs.len() {
        print!(" {}", xs[i]);
    }
    println!();
}


#[allow(unused_imports)]
use std::cmp::{min,max};
#[allow(unused_imports)]
use std::collections::{BTreeMap,BTreeSet};
#[allow(unused_imports)]
use std::ops::*;
#[allow(unused_imports)]
use std::collections::BinaryHeap;

#[allow(unused_macros)]
macro_rules! ite {
    ($c:expr, $t:expr, $f:expr) => {{
        if $c { $t } else { $f }
    }};
}

// ref: tanakh <https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8>
// diff: using Parser
#[macro_export]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut parser = Parser::from_str($s);
        input_inner!{parser, $($r)*}
    };
    (parser = $parser:ident, $($r:tt)*) => {
        input_inner!{$parser, $($r)*}
    };
    (new_stdin_parser = $parser:ident, $($r:tt)*) => {
        let stdin = std::io::stdin();
        let reader = std::io::BufReader::new(stdin.lock());
        let mut $parser = Parser::new(reader);
        input_inner!{$parser, $($r)*}
    };
    ($($r:tt)*) => {
        input!{new_stdin_parser = parser, $($r)*}
    };
}

#[macro_export]
macro_rules! input_inner {
    ($parser:ident) => {};
    ($parser:ident, ) => {};
    ($parser:ident, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($parser, $t);
        input_inner!{$parser $($r)*}
    };
}

#[macro_export]
macro_rules! read_value {
    ($parser:ident, ( $($t:tt),* )) => {
        ( $(read_value!($parser, $t)),* )
    };
    ($parser:ident, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($parser, $t)).collect::<Vec<_>>()
    };
    ($parser:ident, chars) => {
        read_value!($parser, String).chars().collect::<Vec<char>>()
    };
    ($parser:ident, usize1) => {
        read_value!($parser, usize) - 1
    };
    ($parser:ident, $t:ty) => {
        $parser.next::<$t>().expect("Parse error")
    };
}

fn main() {
    input! {
        n: usize,
        xs: [(usize1,usize1); n],
    }
    let mut res = vec![0];
    let mut i = 0;
    while res.len() < n {
        let i1 = xs[i].0;
        let i2 = xs[i].1;
        let (x1, x2) = xs[i1];
        let (y1, y2) = xs[i2];
        let (x1, x2) = {
            if x1 == y1 || x1 == y2 {
                (x1, x2)
            }
            else {
                (x2, x1)
            }
        };
        let (y1, y2) = {
            if x1 == y1 {
                (y1, y2)
            }
            else {
                (y2, y1)
            }
        };
        if x2 == i2 && i1 != 0 {
            res.push(i1);
            i = i1;
        }
        else {
            assert_eq!(y2, i1);
            res.push(i2);
            i = i2;
        }
    }
    print!("{}", res[0] + 1);
    for i in 1..res.len() {
        print!(" {}", res[i] + 1);
    }
    println!();
}

use std::io::BufRead;
use std::io;
use std::str;

// ref: tatsuya6502 <https://qiita.com/tatsuya6502/items/cd448486f7ef7b5b8c7e>
// ref: wariuni <https://qiita.com/tatsuya6502/items/cd448486f7ef7b5b8c7e#comment-7040a5ae96305e884eb9>
// diff: using std::io::BufRead::fill_buf()
pub struct Parser<R> {
    reader: R,
    buf: Vec<u8>,
    pos: usize,
}

impl Parser<io::Empty> {
    pub fn from_str(s: &str) -> Parser<io::Empty> {
        Parser {
            reader: io::empty(),
            buf: s.as_bytes().to_vec(),
            pos: 0,
        }
    }
}

impl<R:BufRead> Parser<R> {
    pub fn new(reader: R) -> Parser<R> {
        Parser {
            reader: reader,
            buf: vec![],
            pos: 0,
        }
    }
    pub fn update_buf(&mut self) {
        self.buf.clear();
        self.pos = 0;
        loop {
            let (len,complete) = {
                let buf2 = self.reader.fill_buf().unwrap();
                self.buf.extend_from_slice(buf2);
                let len = buf2.len();
                (len, buf2[len-1] <= 0x20)
            };
            self.reader.consume(len);
            if complete {
                break;
            }
        }
    }
    pub fn next<T:str::FromStr>(&mut self) -> Result<T, T::Err> {
        loop {
            let mut begin = self.pos;
            while begin < self.buf.len() && (self.buf[begin] <= 0x20) {
                begin += 1;
            }
            let mut end = begin;
            while end < self.buf.len() && (self.buf[end] > 0x20) {
                end += 1;
            }
            if begin != self.buf.len() {
                self.pos = end;
                return str::from_utf8(&self.buf[begin..end]).unwrap().parse::<T>();
            }
            else {
                self.update_buf();
            }
        }
    }
}

use std::fmt::Display;
#[allow(dead_code)]
fn write_vec<T: Display>(xs: &Vec<T>) {
    if xs.len() == 0 {
        println!();
        return;
    }
    print!("{}", xs[0]);
    for i in 1..xs.len() {
        print!(" {}", xs[i]);
    }
    println!();
}


use std::io::{self, BufRead};
fn main(){
	let stdin = io::stdin();
	let mut input = stdin.lock();
	let mut line = String::new();
	input.read_line(&mut line).unwrap();
	let mut count = line.trim().parse().unwrap();
	line.clear();
	let mut neighbours = Vec::with_capacity(count);
	while count > 0{
		input.read_line(&mut line).unwrap();
		let mut pair = line.split_whitespace();
		let first = pair.next().unwrap().parse::<usize>().unwrap() - 1;
		let second = pair.next().unwrap().parse::<usize>().unwrap() - 1;
		line.clear();
		neighbours.push((first, second));
		count -= 1;
	}
	line.shrink_to_fit();
	let mut cur;
	let mut next = neighbours[0].0;
	let mut next_next = neighbours[0].1;
	if neighbours[next].0 == next_next || neighbours[next].1 == next_next{
		cur = next;
		next = next_next;
	}else{
		cur = next_next;
	}
	print!("1 {} {}", cur + 1, next + 1);
	count = neighbours.len() - 3;
	while count > 0{
		if neighbours[cur].0 == next{
			next_next = neighbours[cur].1;
		}else{
			next_next = neighbours[cur].0;
		}
		print!(" {}", next_next + 1);
		cur = next;
		next = next_next;
		count -= 1;
	}
}


package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
)

func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)

	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	pn := make([]int, n + 1)
	pnn := make([]int, n + 1)
	for i := 1;i <= n;i ++ {
		fmt.Fscanf(reader, "%d %d\n", &pn[i], &pnn[i])
	}
	if n == 3 {
		fmt.Printf("1 2 3")
		return
	}

	res := make([]int, n)
	res[0] = 1;
	for i := 0;i < n - 1;i ++ {
		p := res[i]
		if pn[pn[p]] == pnn[p] || pnn[pn[p]] == pnn[p] {
			res[i + 1] = pn[p]
		} else {
			res[i + 1] = pnn[p]
		}
	}
	for i := 0;i < n;i ++ {
		fmt.Printf("%d ", res[i])
	}
}


package main

import (
	"bufio"
	"fmt"
	"os"
)
func swap(a ,b *int) {
	tmp := *a
	*a = *b
	*b = tmp
}
func main() {
	buf := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscanf(buf, "%d\n", &n)
	ans := make([]int ,n)
	mat := make([][]int,n+1)
	for i:=1;i <= n;i++{
		mat[i] = make([]int,2)
		fmt.Fscanf(buf,"%d %d\n",&mat[i][0],&mat[i][1])
	}
	if n == 3{
		fmt.Printf("1 2 3\n")
		return
	}
	ans[0] = 1

	if mat[mat[1][0]][0] == mat[1][1] || mat[mat[1][0]][1] == mat[1][1]{
		ans[1] = mat[1][0]
	}else{
		ans[1] = mat[1][1]
	}
	for i := 2;i < n;i++{
		if mat[ans[i-2]][0] == ans[i-1]{
			ans[i] = mat[ans[i-2]][1]
		}else{
			ans[i] = mat[ans[i-2]][0]
		}
	}
	for i := 0;i < n;i++{
		if i > 0{
			fmt.Printf(" ")
		}
		fmt.Printf("%d",ans[i])
	}
	fmt.Printf("\n")
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"time"
)

func main() {
	start := time.Now()
	defer func() {
		run := time.Since(start)
		_ = run
		// fmt.Println("Run in", run)
	}()

	var stdin *bufio.Reader
	// LOCAL
	f, _ := os.Open("input.txt")
	stdin = bufio.NewReader(f)

	// ONLINE JUDGE
	stdin = bufio.NewReader(os.Stdin)

	var n int
	fmt.Fscan(stdin, &n)

	var a1 = make([]int, n)
	var a2 = make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(stdin, &a1[i], &a2[i])
		a1[i]--
		a2[i]--
	}

	var HasCommon func(int, int) int
	HasCommon = func(i, j int) int {
		switch {
		case a1[i] == a1[j], a1[i] == a2[j]:
			return a1[i]
		case a2[i] == a1[j], a2[i] == a2[j]:
			return a2[i]
		default:
			return -1
		}
	}

	var res = make([]int, n)
	res[0] = 0

	var common = HasCommon(0, a1[0])
	if common == -1 {
		common = HasCommon(0, a2[0])
		res[1] = a2[0]
	} else {
		res[1] = a1[0]
	}

	for i := 2; i < n; i++ {
		res[i] = HasCommon(res[i-1], res[i-2])
	}

	for _, num := range res {
		fmt.Print(num+1, " ")
	}
	fmt.Println()
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var scanner = bufio.NewScanner(os.Stdin)

func scanNum() int {
	scanner.Scan()
	num, _ := strconv.Atoi(scanner.Text())
	return num
}
func main() {
	scanner.Split(bufio.ScanWords)
	n := scanNum()
	if n == 3 {
		fmt.Println("1 2 3")
		os.Exit(0)
	}
	a := make([][2]int, n+1)
	for i := 0; i < n; i++ {
		a[i+1] = [2]int{scanNum(), scanNum()}
	}

	res := []int{1}
	for len(res) < n {
		cur := res[len(res)-1]
		c1, c2 := a[cur][0], a[cur][1]
		next := c1

		c2IsNext := (a[c1][0] != c2) && (a[c1][1] != c2)
		if c2IsNext {
			next = c2
		}

		res = append(res, next)
	}

	fmt.Print(res[0])
	for i := 1; i < n; i++ {
		fmt.Printf(" %d", res[i])
	}
	fmt.Println()
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var scanner = bufio.NewScanner(os.Stdin)

func scanNum() int {
	scanner.Scan()
	num, _ := strconv.Atoi(scanner.Text())
	return num
}
func main() {
	scanner.Split(bufio.ScanWords)
	n := scanNum()
	a := make([][2]int, n+1)
	for i := 0; i < n; i++ {
		a[i+1] = [2]int{scanNum(), scanNum()}
	}

	res := []int{1}
	for len(res) < n {
		cur := res[len(res)-1]
		c1, c2 := a[cur][0], a[cur][1]
		c2IsNext := (a[c1][0] != c2) && (a[c1][1] != c2)

		if c2IsNext {
			res = append(res, c2)
		} else {
			res = append(res, c1)
		}
	}

	fmt.Print(res[0])
	for i := 1; i < n; i++ {
		fmt.Printf(" %d", res[i])
	}
	fmt.Println()
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var scanner = bufio.NewScanner(os.Stdin)

func scanNum() int {
	scanner.Scan()
	num, _ := strconv.Atoi(scanner.Text())
	return num
}
func main() {
	scanner.Split(bufio.ScanWords)
	n := scanNum()
	a := make([][2]int, n+1)
	for i := 0; i < n; i++ {
		a[i+1] = [2]int{scanNum(), scanNum()}
	}

	res, memo := []int{1}, map[int]bool{1: true}
	for len(res) < n {
		cur := res[len(res)-1]
		c1, c2 := a[cur][0], a[cur][1]
		next := c1

		// I think this memo defense will only be used when n === 3
		if !memo[c1] && !memo[c2] {
			c2IsNext := (a[c1][0] != c2) && (a[c1][1] != c2)
			if c2IsNext {
				next = c2
			}
		} else {
			if memo[c1] {
				next = c2
			}
		}

		res, memo[next] = append(res, next), true
	}

	fmt.Print(res[0])
	for i := 1; i < n; i++ {
		fmt.Printf(" %d", res[i])
	}
	fmt.Println()
}


n = input()
e = []
for i in range(n):
    a, b = map(int, raw_input().split())
    e.append((a, b))

z = [1]
i = 0
while i < n - 2:
    x = z[i]
    y1, y2 = e[x - 1]
    if y2 in e[y1 - 1]:
        z.append(y1)
        z.append(y2)
    else:
        z.append(y2)
        z.append(y1)
    i += 2

print ' '.join(map(str, z))


n = input()
e = []
for i in range(n):
    a, b = map(int, raw_input().split())
    e.append((a, b))

z = [1]
v = {}
i = 0
while i < n - 2:
    x = z[i]
    y1, y2 = e[x - 1]
    if y2 in e[y1 - 1]:
        z.append(y1)
        z.append(y2)
    else:
        z.append(y2)
        z.append(y1)
    v[x] = True
    v[y1] = True
    v[y2] = True
    i += 2

if len(z) < n:
    for i in range(1, n + 1):
        if i not in v: z.append(i)

print ' '.join(map(str, z))


#!/usr/bin/env python
"""
This file is part of https://github.com/Cheran-Senthil/PyRival.

Copyright 2018 Cheran Senthilkumar all rights reserved,
Cheran Senthilkumar <hello@cheran.io>
Permission to use, modify, and distribute this software is given under the
terms of the MIT License.

"""
from __future__ import division, print_function

import cmath
import itertools
import math
import operator as op
# import random
import sys
from atexit import register
from bisect import bisect_left, bisect_right
# from collections import Counter, MutableSequence, defaultdict, deque
# from copy import deepcopy
# from decimal import Decimal
# from difflib import SequenceMatcher
# from fractions import Fraction
# from heapq import heappop, heappush

if sys.version_info[0] < 3:
    # from cPickle import dumps
    from io import BytesIO as stream
    # from Queue import PriorityQueue, Queue
else:
    # from functools import reduce
    from io import StringIO as stream
    from math import gcd
    # from pickle import dumps
    # from queue import PriorityQueue, Queue

if sys.version_info[0] < 3:
    class dict(dict):
        """dict() -> new empty dictionary"""
        def items(self):
            """D.items() -> a set-like object providing a view on D's items"""
            return dict.iteritems(self)

        def keys(self):
            """D.keys() -> a set-like object providing a view on D's keys"""
            return dict.iterkeys(self)

        def values(self):
            """D.values() -> an object providing a view on D's values"""
            return dict.itervalues(self)

    def gcd(x, y):
        """greatest common divisor of x and y"""
        while y:
            x, y = y, x % y
        return x

    input = raw_input
    range = xrange

    filter = itertools.ifilter
    map = itertools.imap
    zip = itertools.izip

def sync_with_stdio(sync=True):
    """Set whether the standard Python streams are allowed to buffer their I/O.

    Args:
        sync (bool, optional): The new synchronization setting.

    """
    global input, flush

    if sync:
        flush = sys.stdout.flush
    else:
        sys.stdin = stream(sys.stdin.read())
        input = lambda: sys.stdin.readline().rstrip('\r\n')

        sys.stdout = stream()
        register(lambda: sys.__stdout__.write(sys.stdout.getvalue()))

def main():
    n = int(input())
    sol = [[] for _ in range(n)]
    for i in range(n):
        sol[i] = list(map(lambda x: int(x) - 1, input().split(' ')))

    res = [0]
    while len(res) < n:
        a1, a2 = sol[res[-1]]
        if a1 in sol[a2]:
            res.append(a2)
            res.append(a1)
        else:
            res.append(a1)
            res.append(a2)

    if len(res) == n + 1:
        res.pop()

    print(*map(lambda x: x + 1, res))

if __name__ == '__main__':
    sync_with_stdio(False)
    main()


import sys
n = input()
lhs = []
rhs = []
def solve(a, b):
    ret = [a, b]
    while len(ret) < n:
        if lhs[ret[-2]] == ret[-1]:
            ret.append(rhs[ret[-2]])
        elif rhs[ret[-2]] == ret[-1]:
            ret.append(lhs[ret[-2]])
        else:
            return
    print " ".join([str(x+1) for x in ret])

n = input()
for _ in xrange(n):
    a, b = (int(x) for x in raw_input().split())
    lhs.append(a-1)
    rhs.append(b-1)

solve(0, lhs[0])
solve(0, lhs[1])


import sys
n = int(raw_input())
lhs = []
rhs = []
def solve(a, b):
    ret = [a, b]
    while len(ret) < n:
        if lhs[ret[-2]] == ret[-1]:
            ret.append(rhs[ret[-2]])
        elif rhs[ret[-2]] == ret[-1]:
            ret.append(lhs[ret[-2]])
        else:
            return
    print " ".join([str(x+1) for x in ret])

for _ in xrange(n):
    a, b = (int(x) for x in raw_input().split())
    lhs.append(a-1)
    rhs.append(b-1)

solve(0, lhs[0])
solve(0, rhs[0])


import sys
n = int(raw_input())
lhs = []
rhs = []
def solve(a, b):
    ret = [a, b]
    while len(ret) < n:
        if lhs[ret[-2]] == ret[-1]:
            ret.append(rhs[ret[-2]])
        elif rhs[ret[-2]] == ret[-1]:
            ret.append(lhs[ret[-2]])
        else:
            return
    print " ".join([str(x+1) for x in ret])
    sys.exit(0)

for _ in xrange(n):
    a, b = (int(x) for x in raw_input().split())
    lhs.append(a-1)
    rhs.append(b-1)

solve(0, lhs[0])
solve(0, rhs[0])


from sys import stdin

n = input()
inp = stdin.readlines()

ch = [0 for i in xrange(n)]

for i in xrange(n):
    a, b = map(int, inp[i].strip().split())
    ch[i] = (a - 1, b - 1)

vis = [0 for i in xrange(n)]

link = {}

i = 0
while vis[i] == 0:
    a, b = ch[i]
    if b not in ch[a]:
        assert a in ch[b]
        link[i] = b
        vis[i] = 1
        link[b] = a
        vis[b] = 1

        i = a
    else:
        link[i] = a
        vis[i] = 1
        link[a] = b
        vis[a] = 1

        i = b

out = []
st = 0
while True:
    out.append(st + 1)
    st = link[st]
    if st == 0: break

print ' '.join(map(str, out))


from sys import stdin

n = input()
inp = stdin.readlines()

ch = [0 for i in xrange(n)]

for i in xrange(n):
    a, b = map(int, inp[i].strip().split())
    ch[i] = (a - 1, b - 1)

vis = [0 for i in xrange(n)]

link = {}

i = 0
while vis[i] == 0:
    a, b = ch[i]
    if b in ch[a]:
        link[i] = a
        vis[i] = 1
        link[a] = b
        vis[a] = 1

        i = b
    elif a in ch[b]:
        link[i] = b
        vis[i] = 1
        link[b] = a
        vis[b] = 1

        i = a

out = []
st = 0
while True:
    out.append(st + 1)
    st = link[st]
    if st == 0: break

print ' '.join(map(str, out))


from sys import stdin

n = input()
inp = stdin.readlines()

ch = [0 for i in xrange(n)]

for i in xrange(n):
    a, b = map(int, inp[i].strip().split())
    ch[i] = (a - 1, b - 1)

vis = [0 for i in xrange(n)]

link = {}
for i in xrange(n):
    if vis[i] == 1: continue
    a, b = ch[i]
    if b not in ch[a]:
        link[i] = b
        vis[i] = 1
        link[b] = a
        vis[b] = 1
    else:
        link[i] = a
        vis[i] = 1
        link[a] = b
        vis[a] = 1

out = ['1']
st = link[0]
while st != 0:
    out.append(str(st + 1))
    st = link[st]

print ' '.join(out)


from sys import stdin

n = input()
inp = stdin.readlines()

ch = [0 for i in xrange(n)]

for i in xrange(n):
    a, b = map(int, inp[i].strip().split())
    ch[i] = (a - 1, b - 1)

vis = [0 for i in xrange(n)]

link = {}
for i in xrange(n):
    if vis[i] == 1: continue
    a, b = ch[i]
    if b not in ch[a]:
        if not vis[i]:
            link[i] = b
            vis[i] = 1
        if not vis[b]:
            link[b] = a
            vis[b] = 1
    else:
        if not vis[i]:
            link[i] = a
            vis[i] = 1
        if not vis[a]:
            link[a] = b
            vis[a] = 1

out = ['1']
st = link[0]
while st != 0:
    out.append(str(st + 1))
    st = link[st]

print ' '.join(out)


from sys import stdin

n = input()
inp = stdin.readlines()

if n == 3:
    print 1, 2, 3
    exit()

ch = [0 for i in xrange(n)]

for i in xrange(n):
    a, b = map(int, inp[i].strip().split())
    ch[i] = (a - 1, b - 1)

vis = [0 for i in xrange(n)]

link = {}

i = 0
while vis[i] == 0:
    a, b = ch[i]
    if b in ch[a]:
        link[i] = a
        vis[i] = 1
        link[a] = b
        vis[a] = 1

        i = b
    elif a in ch[b]:
        link[i] = b
        vis[i] = 1
        link[b] = a
        vis[b] = 1

        i = a

out = []
st = 0
while True:
    out.append(st + 1)
    st = link[st]
    if st == 0: break

print ' '.join(map(str, out))


from sys import stdin

n = input()
inp = stdin.readlines()

ch = [0 for i in xrange(n)]

for i in xrange(n):
    a, b = map(int, inp[i].strip().split())
    ch[i] = (a - 1, b - 1)

vis = [0 for i in xrange(n)]

link = {}

i = 0
while vis[i] == 0:
    a, b = ch[i]
    if b not in ch[a]:
        link[i] = b
        vis[i] = 1
        link[b] = a
        vis[b] = 1

        i = a
    elif a not in ch[b]:
        link[i] = a
        vis[i] = 1
        link[a] = b
        vis[a] = 1

        i = b

out = []
st = 0
while True:
    out.append(st + 1)
    st = link[st]
    if st == 0: break

print ' '.join(map(str, out))


#!/usr/bin/python2

import sys
from heapq import *
from collections import Counter

def ir(): return int(raw_input())
def ia(): return map(int, raw_input().split())

n = ir()

a = [None] * n
b = [None] * n
s = set()
for i in xrange(n):
    x, y = ia()
    a[i], b[i] = x, y
    s.add( (x, y) )
    s.add( (y, x) )

nxt = dict()
for i in xrange(n):
    x, y = a[i], b[i]
    i += 1
    if (i, x) in s:
        nxt[i] = x
        nxt[x] = y
    else:
        nxt[i] = y
        nxt[y] = x

if n == 3:
    print 1, 2, 3
else:
    ans = []
    s = s0 = 1
    while True:
        ans.append(s)
        s = nxt[s]
        if s == s0: break
    print " ".join(map(str, ans))


#!/usr/bin/python2

import sys
from heapq import *
from collections import Counter

def ir(): return int(raw_input())
def ia(): return map(int, raw_input().split())

n = ir()

a = [None] * n
b = [None] * n
s = set()
for i in xrange(n):
    x, y = ia()
    a[i], b[i] = x, y
    s.add( (x, y) )
    s.add( (y, x) )

nxt = dict()
for i in xrange(n):
    x, y = a[i], b[i]
    if (i + 1, x) in s:
        nxt[x] = y
    else:
        nxt[y] = x

ans = []
s = s0 = 1
while True:
    ans.append(s)
    s = nxt[s]
    if s == s0: break

print " ".join(map(str, ans))