【栈】LeetCode 1472. 设计浏览器历史记录
题目链接
思路
用栈 history
模拟网页的前进后退操作,用栈 temp
来暂时存储后退所退出的网页。
代码
class BrowserHistory{
Stack<String> history;
Stack<String> temp;
public BrowserHistory(String homepage){
this.history = new Stack<>();
this.history.push(homepage);
this.temp = new Stack<>();
}
public void visit(String url){
this.history.push(url);
this.temp.clear();
}
public String back(int steps){
while(steps > 0 && this.history.size() > 1){
this.temp.push(this.history.pop());
steps--;
}
return this.history.peek();
}
public String forward(int steps){
while(steps > 0 && this.temp.size() > 0){
this.history.push(this.temp.pop());
steps--;
}
return this.history.peek();
}
}