fork download
  1. #include <iostream>
  2. #include <stack>
  3. #include <string>
  4.  
  5. using namespace std;
  6.  
  7. class TextEditor {
  8. private:
  9. stack<string> undoStack;
  10. stack<string> redoStack;
  11. string text;
  12.  
  13. public:
  14. void write(const string& newText) {
  15. undoStack.push(text); // Save current state before modification
  16. text = newText;
  17. while (!redoStack.empty()) redoStack.pop(); // Clear redo stack
  18. }
  19.  
  20. void undo() {
  21. if (!undoStack.empty()) {
  22. redoStack.push(text); // Save current state for redo
  23. text = undoStack.top(); // Restore previous state
  24. undoStack.pop();
  25. } else {
  26. cout << "Nothing to undo!\n";
  27. }
  28. }
  29.  
  30. void redo() {
  31. if (!redoStack.empty()) {
  32. undoStack.push(text); // Save current state for undo
  33. text = redoStack.top(); // Restore undone state
  34. redoStack.pop();
  35. } else {
  36. cout << "Nothing to redo!\n";
  37. }
  38. }
  39.  
  40. void display() {
  41. cout << "Current Text: " << text << endl;
  42. }
  43. };
  44.  
  45. int main() {
  46. TextEditor editor;
  47. editor.write("Hello");
  48. editor.display();
  49.  
  50. editor.write("Hello World");
  51. editor.display();
  52.  
  53. editor.undo();
  54. editor.display();
  55.  
  56. editor.redo();
  57. editor.display();
  58.  
  59. return 0;
  60. }
  61.  
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
Current Text: Hello
Current Text: Hello World
Current Text: Hello
Current Text: Hello World