Implementing Stack in C++ || Data Structure

How Browser maintains multiple pages using 

the Forward and Backward buttons?





There are multiple ways through which we can make a similar system that will work like browsers forward and backward buttons. Here I'm going to make this system using the STACK data structure.
Now we will learn what is the stack?

Stack

stack is a conceptual structure consisting of a set of homogeneous elements and is based on the principle of last in first out (LIFO). For example, let's think about a stack of books. If we need a book from the middle of it we can not just take that book. In order to take that particular book, we have to go through from the top to the particular book one by one. It means we can pick the last book we placed on that stack of books. It follows the LIFO(Last in First out) order.

In easy language -  Stack is a data structure where we can put our data on the top and pick the data also from the top.




In order to solve the problem, we need two stacks one for the Backward button and one for the Forward button.

Similar problem link:  Discover the Web | LightOJ

I am using C++ for solving the problem-

In C++ we can use stack by the following commands

///Declaring a stack;
stack<data_type> name;

///For pushing the data into the stack
name.push(Data);

///For reading the top data of the stack
name.top();

///For removing the top data from the stack
name.pop();

///For getting the size of the stack
name.size();



The solution in C++



/// BISMILLAHIR RAHMANIR RAHIM
/// TANVIR AHMED KHAN
///CONTACT  : +8801625090976, mostlytanvir@gmail.com
#include<bits/stdc++.h>
using namespace std;
int main()
{
    int tc;cin>>tc;
    while(tc--)
    {
        stack<string>Back;
        stack<string>Forward;
        Back.push("http://www.lightoj.com/");
        string s,url,temp;
        while(cin>>s && s!="QUIT")
        {
            if(s=="VISIT")
            {
                cin>>url;
                Back.push(url);
                cout<<url<<endl;
                while(!Forward.empty())Forward.pop();
            }
            else if(s=="BACK"&& (Back.size()>1))
            {
                temp = Back.top();
                Forward.push(temp);
                Back.pop();
                cout<<Back.top()<<endl;
            }
            else if(s=="FORWARD"&& (Forward.size()>0))
            {
                temp = Forward.top();
                Back.push(temp);
                Forward.pop();
                cout<<Back.top()<<endl;
            }
            else cout<<"Ignored\n";
        }
    }
    return 0;
}



Comments