How to implement undo and redo operations
1 min readJul 3, 2021
--
Undo and Redo operations can be implemented with the help of 2 stacks.
- Push all operations to Undo stack.
- When undo is called, pop operations from Undo stack and push it to Redo stack.
- When redo is called, pop operations from Redo stack and push it to Undo stack.
package mainimport (
"fmt"
)type stack []stringvar undoStack *stack
var redoStack *stackfunc (s *stack) isEmpty() bool {
return len(*s) == 0
}func (s *stack) push(val string) {
*s = append(*s, val)
fmt.Println("Pushed : ", val)
}func (s *stack) pop() (string, bool) {
if s.isEmpty() {
return "", false
}
lstIdx := len(*s) - 1
top := (*s)[lstIdx]
*s = (*s)[:lstIdx]
return top, true
}func undo() {
if val, ok := undoStack.pop(); ok {
redoStack.push(val)
fmt.Printf("\nchanges for %s undone\n", val)
}
}func redo() {
if val, ok := redoStack.pop(); ok {
undoStack.push(val)
fmt.Printf("\nchanges for %s reverted\n", val)
}
}func main() {
undoStack = new(stack)
redoStack = new(stack) undoStack.push("World")
undoStack.push("is")
undoStack.push("beautiful")
undoStack.push("Hello")
undoStack.push("Listener")
undo()
undo()
redo()
redo()
}