fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. struct ChangeNode
  6. {
  7. string text;
  8. ChangeNode* next;
  9. ChangeNode* pre;
  10. ChangeNode(string t)
  11. {
  12. text = t;
  13. next = nullptr;
  14. pre = nullptr;
  15. }
  16. };
  17.  
  18. class editor
  19. {
  20. private:
  21. ChangeNode* current;
  22.  
  23. public:
  24. //Khoi tao
  25. editor() : current(new ChangeNode("")) {}
  26.  
  27. void type(const string &newText)
  28. {
  29. ChangeNode* newNode = new ChangeNode(newText);
  30. newNode->pre = current;
  31. current->next = newNode;
  32. current = newNode;
  33. cout << "Typed: " << newText << ". Current text: " << getText() << endl;
  34. }
  35.  
  36. string undo()
  37. {
  38. if (current != nullptr && current->pre != nullptr) {
  39. current = current->pre;
  40. cout << "Undo. Current text: " << getText() << endl;
  41. return current->text;
  42. } else {
  43. cout << "Cannot undo further." << endl;
  44. return getText();
  45. }
  46. }
  47.  
  48. string redo()
  49. {
  50. if (current != nullptr && current->next != nullptr)
  51. {
  52. current = current->next;
  53. cout << "Redo. Current text: " << getText() << endl;
  54. return current->text;
  55. }
  56. else
  57. {
  58. cout << "Cannot redo further." << endl;
  59. return getText();
  60. }
  61. }
  62.  
  63. string getText() const
  64. {
  65. return current->text;
  66. }
  67.  
  68. ~editor()
  69. {
  70. ChangeNode* temp;
  71. while (current != nullptr && current->pre != nullptr)
  72. {
  73. current = current->pre;
  74. }
  75. while (current != nullptr)
  76. {
  77. temp = current;
  78. current = current->next;
  79. delete temp;
  80. }
  81. }
  82. };
  83.  
  84. int main()
  85. {
  86. editor e;
  87. e.type("Hello");
  88. e.type(" ");
  89. e.type("World");
  90.  
  91. e.undo();
  92. e.undo();
  93. e.redo();
  94.  
  95. cout << "Final text: " << e.getText() << endl;
  96.  
  97. return 0;
  98. }
Success #stdin #stdout 0.01s 5292KB
stdin
Standard input is empty
stdout
Typed: Hello. Current text: Hello
Typed:  . Current text:  
Typed: World. Current text: World
Undo. Current text:  
Undo. Current text: Hello
Redo. Current text:  
Final text: