Implementing Backward and Forward buttons of Browser

27 Aug, 2021
Design the forward and backward buttons of a Browser using Stack Data Structure. If at any instance, the URL does not exist after pressing any of the two buttons, then print “Not Available”. Otherwise, print the current URL.
Approach: The idea is to use two stacks backward and forward to keep track of visited URLs and a variable “currentStateURL” to store the currently visited URL. Follow the steps below to solve the problem:
Initialize currentStateURL that will store the current URL of the Browser.
Initialize two stacks forwardStack and backwardStack that will store the sequence of URLs accessed when the forward and the backward buttons are pressed respectively.
While visiting any new URL, push it into backwardStack.
While pressing the forward button push currentStateURL into backwardStack and pop the last URL from forwardStack and set it as currentStateURL.
While pressing the backward button, push currentStateURL into forwardStack and pop the last URL from backwardStack, and set it as currentStateURL.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Stores the current visiting pagestring current_state_url = ""; // Stores url when pressed forwardstack<string> forward_stack; // Stores url when pressed backwardstack<string> backward_stack; // Function for when visit a urlvoid visit_new_url(string url){    // If current URL is empty    if (current_state_url != "") {         // Push into backward_stack        backward_stack.push(            current_state_url);    }     // Set curr_state_url to url    current_state_url = url;} // Function to handle state when the// forward button is pressedvoid forward(){    // If current url is the last url    if (forward_stack.empty()        || current_state_url               == forward_stack.top()) {        cout << "Not Available\n";        return;    }     // Otherwise    else {         // Push current state to the        // backward stack        backward_stack.push(            current_state_url);         // Set current state to top        // of forward stack        current_state_url            = forward_stack.top();         // Remove from forward stack        forward_stack.pop();    }} // Function to handle state when the// backward button is pressedvoid backward(){    // If current url is the last url    if (backward_stack.empty()        || current_state_url               == backward_stack.top()) {         cout << "Not Available\n";        return;    }     // Otherwise    else {         // Push current url to the        // forward stack        forward_stack.push(            current_state_url);         // Set current url to top        // of backward stack        current_state_url            = backward_stack.top();         // Pop it from backward stack        backward_stack.pop();    }} // Function that performs the process// of pressing forward and backward// button in a Browservoid simulatorFunction(){    // Current URL    string url = "ajay.com";     // Visit the current URL    visit_new_url(url);     // Print the current URL    cout << "Current URL is: "         << current_state_url         << " \n";     // New current URL    url = "abc.com";     // Visit the current URL    visit_new_url(url);     // Print the current URL    cout << "Current URL is: "         << current_state_url         << " \n";     // Pressed backward button    backward();     // Print the current URL    cout << "Current URL after pressing"         << " Backward button is: "         << current_state_url         << " \n";     // Pressed forward button    forward();     // Print the current URL    cout << "Current URL after pressing"         << " Forward button is: "         << current_state_url         << " \n";     // New current URL    url = "nikhil.com";     // Visit the current URL    visit_new_url(url);     // Print the current URL    cout << "Current URL is: "         << current_state_url         << " \n";     // Pressed forward button    forward();     // Print the current URL    cout << "Current URL after pressing"         << " Forward button is: "         << current_state_url         << " \n";    // Pressed backward button    backward();     // Print the current URL    cout << "Current URL after pressing"         << " Backward button is: "         << current_state_url         << " \n";} // Driver Codeint main(){    // Function to simulate process of    // pressing forward & backward button    simulatorFunction();}
// Java program for the// above approachimport java.util.*;class GFG{ // Stores the current// visiting pagestatic String current_state_url = ""; // Stores url when pressed forwardstatic Stack<String>       forward_stack = new Stack<>(); // Stores url when pressed backwardstatic Stack<String>       backward_stack = new Stack<>(); // Function for when visit a urlstatic void visit_new_url(String url){  // If current URL is empty  if (current_state_url != "")  {    // Push into backward_stack    backward_stack.add(             current_state_url);  }   // Set curr_state_url to url  current_state_url = url;} // Function to handle state// when the forward button// is pressedstatic void forward(){  // If current url is the last url  if (forward_stack.isEmpty() ||      current_state_url ==      forward_stack.peek())  {    System.out.print("Not Available\n");    return;  }   // Otherwise  else  {    // Push current state to the    // backward stack    backward_stack.add(             current_state_url);     // Set current state to top    // of forward stack    current_state_url =            forward_stack.peek();     // Remove from forward    // stack    forward_stack.pop();  }} // Function to handle state// when the backward button// is pressedstatic void backward(){  // If current url is the  // last url  if (backward_stack.isEmpty() ||      current_state_url ==      backward_stack.peek())  {    System.out.print("Not Available\n");    return;  }   // Otherwise  else  {    // Push current url to the    // forward stack    forward_stack.add(            current_state_url);     // Set current url to top    // of backward stack    current_state_url =            backward_stack.peek();     // Pop it from backward    // stack    backward_stack.pop();  }} // Function that performs the// process of pressing forward// and backward button in a// Browserstatic void simulatorFunction(){  // Current URL  String url = "ajay.com";   // Visit the current URL  visit_new_url(url);   // Print the current URL  System.out.print("Current URL is: " +                   current_state_url +                   " \n");   // New current URL  url = "abc.com";   // Visit the current URL  visit_new_url(url);   // Print the current URL  System.out.print("Current URL is: " +                   current_state_url +                   " \n");   // Pressed backward button  backward();   // Print the current URL  System.out.print("Current URL after pressing" +                   " Backward button is: " +                   current_state_url + " \n");   // Pressed forward button  forward();   // Print the current URL  System.out.print("Current URL after pressing" +                   " Forward button is: " +                   current_state_url + " \n");     // New current URL    url = "nikhil.com";     // Visit the current URL    visit_new_url(url);     // Print the current URL    System.out.print("Current URL is: " +                     current_state_url +                     " \n");     // Pressed forward button    forward();     // Print the current URL    System.out.print("Current URL after pressing" +                     " Forward button is: " +                     current_state_url + " \n");    // Pressed backward button    backward();     // Print the current URL    System.out.print("Current URL after pressing" +                     " Backward button is: " +                     current_state_url + " \n");} // Driver Codepublic static void main(String[] args){  // Function to simulate process of  // pressing forward & backward button  simulatorFunction();}} // This code is contributed by shikhasingrajput
# Python3 program for the above approach # Stores the current# visiting pagecurrent_state_url = ""  # Stores url when pressed forwardforward_stack = []  # Stores url when pressed backwardbackward_stack = []     # Function for when visit a urldef visit_new_url(url):  global current_state_url     # If current URL is empty  if (current_state_url != ""):    # Push into backward_stack    backward_stack.append(current_state_url)    # Set curr_state_url to url  current_state_url = url  # Function to handle state# when the forward button# is presseddef forward():  # If current url is the last url  if (len(forward_stack) == 0 or current_state_url == forward_stack[-1]):    print("Not Available")    return    # Otherwise  else:    # Push current state to the    # backward stack    backward_stack.append(current_state_url)      # Set current state to top    # of forward stack    current_state_url = forward_stack[-1]      # Remove from forward    # stack    forward_stack.pop()  # Function to handle state# when the backward button# is presseddef backward():  # If current url is the  # last url  if (len(backward_stack) != 0 or current_state_url == backward_stack[-1]):    print("Not Available")    return    # Otherwise  else:    # Push current url to the    # forward stack    forward_stack.append(current_state_url)      # Set current url to top    # of backward stack    current_state_url = backward_stack[-1]      # Pop it from backward    # stack    backward_stack[-1]  # Function that performs the# process of pressing forward# and backward button in a# Browserdef simulatorFunction():  # Current URL  url = "ajay.com"    # Visit the current URL  visit_new_url(url)    # Print the current URL  print("Current URL is: " + current_state_url)    # New current URL  url = "abc.com"    # Visit the current URL  visit_new_url(url)    # Print the current URL  print("Current URL is: " + current_state_url)    # Pressed backward button  backward()    # Print the current URL  print("Current URL after pressing" + " Backward button is: " + current_state_url)    # Pressed forward button  forward()    # Print the current URL  print("Current URL after pressing" + " Forward button is: " + current_state_url)    # New current URL  url = "nikhil.com"    # Visit the current URL  visit_new_url(url)    # Print the current URL  print("Current URL is: " + current_state_url)    # Pressed forward button  forward()    # Print the current URL  print("Current URL after pressing" + " Forward button is: " + current_state_url)  # Pressed backward button  backward()    # Print the current URL  print("Current URL after pressing" + " Backward button is: " + current_state_url)   # Function to simulate process of# pressing forward & backward buttonsimulatorFunction() # This code is contributed by suresh07.
// C# program for the// above approachusing System;using System.Collections.Generic;class GFG{ // Stores the current// visiting pagestatic String current_state_url = ""; // Stores url when pressed forwardstatic Stack<String>       forward_stack = new Stack<String>(); // Stores url when pressed backwardstatic Stack<String>       backward_stack = new Stack<String>();      // Function for when visit a urlstatic void visit_new_url(String url){  // If current URL is empty  if (current_state_url != "")  {    // Push into backward_stack    backward_stack.Push(             current_state_url);  }   // Set curr_state_url to url  current_state_url = url;} // Function to handle state// when the forward button// is pressedstatic void forward(){  // If current url is the last url  if (forward_stack.Count == 0 ||      current_state_url ==      forward_stack.Peek())  {    Console.Write("Not Available\n");    return;  }   // Otherwise  else  {    // Push current state to the    // backward stack    backward_stack.Push(             current_state_url);     // Set current state to top    // of forward stack    current_state_url =            forward_stack.Peek();     // Remove from forward    // stack    forward_stack.Pop();  }} // Function to handle state// when the backward button// is pressedstatic void backward(){  // If current url is the  // last url  if (backward_stack.Count != 0 ||      current_state_url ==      backward_stack.Peek())  {    Console.Write("Not Available\n");    return;  }   // Otherwise  else  {    // Push current url to the    // forward stack    forward_stack.Push(            current_state_url);     // Set current url to top    // of backward stack    current_state_url =            backward_stack.Peek();     // Pop it from backward    // stack    backward_stack.Pop();  }} // Function that performs the// process of pressing forward// and backward button in a// Browserstatic void simulatorFunction(){  // Current URL  String url = "ajay.com";   // Visit the current URL  visit_new_url(url);   // Print the current URL  Console.Write("Current URL is: " +                current_state_url +                " \n");   // New current URL  url = "abc.com";   // Visit the current URL  visit_new_url(url);   // Print the current URL  Console.Write("Current URL is: " +                current_state_url +                " \n");   // Pressed backward button  backward();   // Print the current URL  Console.Write("Current URL after pressing" +                " Backward button is: " +                current_state_url + " \n");   // Pressed forward button  forward();   // Print the current URL  Console.Write("Current URL after pressing" +                " Forward button is: " +                current_state_url + " \n");   // New current URL  url = "nikhil.com";   // Visit the current URL  visit_new_url(url);   // Print the current URL  Console.Write("Current URL is: " +                current_state_url +                " \n");   // Pressed forward button  forward();   // Print the current URL  Console.Write("Current URL after pressing" +                " Forward button is: " +                current_state_url + " \n");  // Pressed backward button  backward();   // Print the current URL  Console.Write("Current URL after pressing" +                " Backward button is: " +                current_state_url + " \n");} // Driver Codepublic static void Main(String[] args){  // Function to simulate process of  // pressing forward & backward button  simulatorFunction();}} // This code is contributed by shikhasingrajput
<script>    // Javascript program for the above approach         // Stores the current    // visiting page    let current_state_url = "";     // Stores url when pressed forward    let forward_stack = [];     // Stores url when pressed backward    let backward_stack = [];      // Function for when visit a url    function visit_new_url(url)    {      // If current URL is empty      if (current_state_url != "")      {        // Push into backward_stack        backward_stack.push(current_state_url);      }       // Set curr_state_url to url      current_state_url = url;    }     // Function to handle state    // when the forward button    // is pressed    function forward()    {      // If current url is the last url      if (forward_stack.length == 0 ||          current_state_url == forward_stack[forward_stack.length - 1])      {        document.write("Not Available" + "</br>");        return;      }       // Otherwise      else      {        // Push current state to the        // backward stack        backward_stack.push(current_state_url);         // Set current state to top        // of forward stack        current_state_url = forward_stack[forward_stack.length - 1];         // Remove from forward        // stack        forward_stack.pop();      }    }     // Function to handle state    // when the backward button    // is pressed    function backward()    {      // If current url is the      // last url      if (backward_stack.length != 0 ||          current_state_url ==          backward_stack[backward_stack.length - 1])      {        document.write("Not Available" + "</br>");        return;      }       // Otherwise      else      {        // Push current url to the        // forward stack        forward_stack.push(current_state_url);         // Set current url to top        // of backward stack        current_state_url = backward_stack[backward_stack.length - 1];         // Pop it from backward        // stack        backward_stack.pop();      }    }     // Function that performs the    // process of pressing forward    // and backward button in a    // Browser    function simulatorFunction()    {      // Current URL      let url = "ajay.com";       // Visit the current URL      visit_new_url(url);       // Print the current URL      document.write("Current URL is: " + current_state_url + "</br>");       // New current URL      url = "abc.com";       // Visit the current URL      visit_new_url(url);       // Print the current URL      document.write("Current URL is: " + current_state_url + "</br>");       // Pressed backward button      backward();       // Print the current URL      document.write("Current URL after pressing" + " Backward button is: " +                    current_state_url + " </br>");       // Pressed forward button      forward();       // Print the current URL      document.write("Current URL after pressing" +                    " Forward button is: " +                    current_state_url + " </br>");       // New current URL      url = "nikhil.com";       // Visit the current URL      visit_new_url(url);       // Print the current URL      document.write("Current URL is: " +                    current_state_url +                    " </br>");       // Pressed forward button      forward();       // Print the current URL      document.write("Current URL after pressing" +                    " Forward button is: " +                    current_state_url + " </br>");      // Pressed backward button      backward();       // Print the current URL      document.write("Current URL after pressing" +                    " Backward button is: " +                    current_state_url + " </br>");    }         // Function to simulate process of    // pressing forward & backward button    simulatorFunction(); // This code is contributed by rameshtravel07.</script>
Current URL is: ajay.com 
Current URL is: abc.com 
Current URL after pressing Backward button is: ajay.com 
Current URL after pressing Forward button is: abc.com 
Current URL is: nikhil.com 
Not Available
Current URL after pressing Forward button is: nikhil.com 
Current URL after pressing Backward button is: abc.com 
 
Time Complexity: O(N). Auxiliary Space: O(N).
shikhasingrajput
surinderdawra388
pankajsharmagfg
suresh07
rameshtravel07
cpp-stack
Data Structures
Stack
Data Structures
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Hashing | A Complete Tutorial
Find if there is a path between two vertices in an undirected graph
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
TCS NQT Coding Sheet
Stack Data Structure (Introduction and Program)
Stack in Python
Stack Class in Java
Check for Balanced Brackets in an expression (well-formedness) using Stack
Introduction to Data Structures