1472.Design Browser History
Question Link:https://leetcode.com/problems/design-browser-history/
Explanation:
The question is asking to perform four operation basically :
BrowserHistory(string homepage)Initializes the object with thehomepageof the browser.void visit(string url)Visitsurlfrom the current page. It clears up all the forward history.string back(int steps)Movestepsback in history. If you can only returnxsteps in the history andsteps > x, you will return onlyxsteps. Return the currenturlafter moving back in history at moststeps.string forward(int steps)Movestepsforward in history. If you can only forwardxsteps in the history andsteps > x, you will forward onlyxsteps. Return the currenturlafter forwarding in history at moststeps.
As we can move both forward and backward direction and need flexibility to move current place to given url .
The datastucture comes to mind is :Doubly Linkedlist bcaz we have to go forward as well as backward direction and all should be connected. First we need to create template for doubly linked list :
class Node{
public:
string url;
Node* prev;
Node* next;
Node(string url){
this->url = url;
prev = NULL;
next = NULL;
}
};
Now we are ready to implement four function
First one is Browser History , Here just we need to initialize object with given url .
class BrowserHistory {
private:
Node *root;
public:
BrowserHistory(string homepage) {
root = new Node(homepage);
}
Now second one visit, we have to add new tab with given url and connect both (for that we are using simply doubly linked list).
void visit(string url) {
Node* node = new Node(url);
root->next = node;
node->prev = root;
root = root->next;
}
Third : Back :just we have to traverse back to get desired url.
string back(int steps) {
for(int i = 0; i<steps && root->prev != NULL; i++){
root = root->prev;
}
return root->url;
}
Fourth Forward: just we have to traverse next to get desired url.
string forward(int steps) {
for(int i = 0; i<steps && root->next != NULL; i++){
root = root->next;
}
return root->url;
}