How to implement undo and redo operations

  • 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 *stack
func (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()
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Prince Pereira

Prince Pereira

31 Followers

Software Engineer II - Microsoft | SDN | Java | Golang | DS & Algo | Microservices | Kubernetes | Docker | gRPC & Protocol Buffer