fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. struct Node {
  6. string url;
  7. Node* pre;
  8. Node(string u)
  9. {
  10. url = u;
  11. pre = nullptr;
  12. }
  13. };
  14.  
  15. class BrowserHis
  16. {
  17. private:
  18. Node* current;
  19.  
  20. public:
  21. BrowserHis(){
  22. current = nullptr;
  23. }
  24.  
  25. void visit(const string& url)
  26. {
  27. Node* newPage = new Node(url);
  28. newPage->pre = current;
  29. current = newPage;
  30. cout << "Visited: " << url << endl;
  31. }
  32.  
  33. string back() {
  34. if (current != nullptr && current->pre != nullptr)
  35. {
  36. current = current->pre;
  37. cout << "Going back to: " << current->url << endl;
  38. return current->url;
  39. }
  40. else
  41. {
  42. cout << "Cannot go back further." << endl;
  43. return "";
  44. }
  45. }
  46.  
  47. string getCurrentPage() const
  48. {
  49. if (current != nullptr) return current->url;
  50. else return "No history.";
  51. }
  52.  
  53. // Giai phong bo nho
  54. ~BrowserHis() {
  55. Node* tmp;
  56. while (current != nullptr)
  57. {
  58. tmp = current;
  59. current = current->pre;
  60. delete tmp;
  61. }
  62. }
  63. };
  64.  
  65. int main() {
  66. BrowserHis his;
  67. his.visit("google.com");
  68. his.visit("facebook.com");
  69. his.visit("youtube.com");
  70.  
  71. cout << "Current page: " << his.getCurrentPage() << endl;
  72.  
  73. his.back();
  74. cout << "Current page: " << his.getCurrentPage() << endl;
  75.  
  76. his.back();
  77. cout << "Current page: " << his.getCurrentPage() << endl;
  78.  
  79. his.back();
  80.  
  81. return 0;
  82. }
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
Visited: google.com
Visited: facebook.com
Visited: youtube.com
Current page: youtube.com
Going back to: facebook.com
Current page: facebook.com
Going back to: google.com
Current page: google.com
Cannot go back further.