// Program to demonstrate the usage of stacks by // modeling a browser back button import java.util.*; public class Browser { public static void main(String[] args) { Stack history = new Stack(); visit("www.google.com", history); visit("cs.washington.edu/143x", history); System.out.println(history); visit("www.facebook.com", history); System.out.println(history); System.out.println(); goBack(history); System.out.println(history); visit("www.fivethirtyeight.com", history); System.out.println(history); goBack(history); goBack(history); goBack(history); System.out.println(history); } // visit the given page // pre: history != null public static void visit(String page, Stack history) { System.out.println("Visiting " + page); history.push(page); } // go back from the current page to the previous one // pre: history != null public static void goBack(Stack history) { String lastPage = history.pop(); System.out.println("Leaving " + lastPage + "..."); if (history.isEmpty()) { System.out.println(" No pages left."); } else { String newPage = history.pop(); System.out.println(" Back to " + newPage); history.push(newPage); } } }