Preview:
import java.util.*;

public class Main {
	public static void main(String[] args) {
		Scanner scn = new Scanner(System.in);
		int noofpairs_src_des = scn.nextInt();
		HashMap<String, String> map = new HashMap<>();
		for (int i = 0; i < noofpairs_src_des; i++) {
			String s1 = scn.next();
			String s2 = scn.next();
			map.put(s1, s2);	
		}

		HashMap<String ,Boolean> set = new HashMap<>();
		
		//sp = starting point,ep=ending point 
		
		for(String sp : map.keySet()){
		    String ep = map.get(sp);
		    
		    set.put(ep,false);
		    if(set.containsKey(sp)==false){
		      set.put(sp,true);  
		    }
		}       
        
        String sp = "";
        for(String p : set.keySet()){
            if(set.get(p)==true){
                sp = p;
                break;
            }
            
        }
        
        while(true){
            if(map.containsKey(sp)==true){
                System.out.println(sp+" -> ");
                sp = map.get(sp);
            }
            else{
                System.out.println(sp+".");
                break
            }
        }
	}
}
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter