Two Stacks, Pretty code.
It\u2019s not difficult to realize that we need a stack so that back can be implemented. However, what to do for forward. Because you want the ability to visit 
It\u2019s not difficult to realize that we need a stack so that `back` can be implemented. However, what to do for `forward`. Because you want the ability to visit all pages in the backward as well as the forward direction, we need to store the URLs whenever we go back. If you see the order in which we want to visit, you will quickly realize that we need two stacks. One to store history and another to store the next URLs in case we go back.\n![image](https://assets.leetcode.com/users/interviewrecipes/image_1591684752.png)\n\nTwo special cases:\nYou must always have at least one element in the history stack which is the page that you are currently at.\nBut for the forward stack, this condition is not necessary.\n\nI am sure the following code will make it even clearer.\n\n**Thanks**\nPlease upvote if you find this helpful, it encourages me to write.\n\n**More?**\nKindly visit my blog.\n\n```\nclass BrowserHistory {\npublic:\n    stack<string> history;\n    stack<string> future;\n\t\n    BrowserHistory(string homepage) {\n        history.push(homepage);\n        future = stack<string>();           // Reset the forward stack.\n    }\n    \n    void visit(string url) {\n        history.push(url);\n        future = stack<string>();           // Reset the forward stack.\n    }\n    \n    string back(int steps) {\n        while(steps > 0 && history.size() > 1) { // Always keep at least one element in the stack. \n            future.push(history.top());\n            history.pop();\n            steps--;\n        }\n        return history.top();\n    }\n    \n    string forward(int steps) {\n        while(steps > 0 && future.size() > 0) {\n            history.push(future.top());\n            future.pop();\n            steps--;\n        }\n        return history.top();\n    }\n};\n\n/**\n * Your BrowserHistory object will be instantiated and called as such:\n * BrowserHistory* obj = new BrowserHistory(homepage);\n * obj->visit(url);\n * string param_2 = obj->back(steps);\n * string param_3 = obj->forward(steps);\n */\n```\n\n
['Stack']