浏览器前进后退:
当你依次浏览a,b,c,然后回到b,再浏览d,就只能查看a,b,d,了。
原理: 利用两个栈A,B
- 浏览新网页的时候,压入栈A,清空栈B
- 前进,栈A获取栈B的栈顶元素,栈B弹栈,并压入栈A
- 后退,栈B获取栈A的栈顶元素,栈A弹栈,并压入栈B
题目:LeetCode 5430. 设计浏览器历史记录(双栈)
browser.h头文件
//
// Created by mingm on 2019/3/31.
//
#ifndef STACK_BROWSER_H
#define STACK_BROWSER_H#include "stack.cpp"
class Browser
{
private:Stack<const char*> forward_stack, back_stack;void displayCurWeb(const char *ch){cout << "Current web is : " << ch << endl;}
public:Browser(){}~Browser(){}void forward(){if(!back_stack.Empty()){forward_stack.Push(back_stack.GetTop()->data);back_stack.Pop();displayCurWeb(forward_stack.GetTop()->data);}else{cout << "can not forward, there is no more page!" << endl;displayCurWeb(forward_stack.GetTop()->data);}}void back(){if(forward_stack.GetLength()>1){back_stack.Push(forward_stack.GetTop()->data);forward_stack.Pop();displayCurWeb(forward_stack.GetTop()->data);}else{cout << "can not back, there is no more page! " << endl;displayCurWeb(forward_stack.GetTop()->data);}}void browseWeb(const char* ch){back_stack.Clear();forward_stack.Push(ch);displayCurWeb(forward_stack.GetTop()->data);}
};
#endif //STACK_BROWSER_H
测试程序 browser_stack_main.cpp
//浏览器前进后退功能,栈实现
// Created by mingm on 2019/3/31.
//
#include "browser.h"
#include <iostream>
using namespace std;int main()
{Browser webBrowser;webBrowser.browseWeb("baidu.com");webBrowser.browseWeb("google.com");webBrowser.browseWeb("163.com");cout << "forward..." << endl;webBrowser.forward();cout << "back..." << endl;webBrowser.back();cout << "browse mi.com ..." << endl;webBrowser.browseWeb("mi.com");cout << "forward..." << endl;webBrowser.forward();cout << "back..." << endl;webBrowser.back();cout << "back..." << endl;webBrowser.back();cout << "back..." << endl;webBrowser.back();cout << "forward..." << endl;webBrowser.forward();
}