Undo, redo and queues
Stacks and queues are two of the most useful data structures. This lesson builds undo and redo from two stacks and a job queue that serves the oldest job first.
What you will learn#
- stack: last in, first out; queue: first in, first out,
Push,Pop,Peek,Enqueue,Dequeue,Count,- building undo and redo with two stacks,
- what happens when you take from an empty collection.
Two ways to wait#
A stack is a pile of plates: you put on top and take from the top. A queue is a line at a shop: the first to arrive is served first.
| Stack | Queue | |
|---|---|---|
| add | Push(x) | Enqueue(x) |
| take | Pop() | Dequeue() |
| look | Peek() | Peek() |
| size | Count | Count |
| used for | undo, the Back button, parsing, the call stack | print jobs, tasks to do, messages |
The ready-made Ring classes are StringStack and StringQueue (see Collections).
The program#
# stacks and queues - undo/redo with two stacks, and a first-come-first-served job queue
load "dotnet.ring"
using {
"System.Collections.Generic"
}
func main
# A STACK: last in, first out (a pile of plates). A QUEUE: first in, first out (people waiting in a line).
# 1. Stack basics
oStack = new StringStack()
oStack.Push("a")
oStack.Push("b")
oStack.Push("c")
? "1. Peek (look at the top): " + oStack.Peek() + ", Pop (take it): " + oStack.Pop() + ", now " + oStack.Count + " items, the top is " + oStack.Peek()
# 2. Undo and redo with two stacks: every change pushes the old text on the undo stack; Undo moves a text to the redo stack
oEditor = new TextHistory()
oEditor.type("Hello")
oEditor.type("Hello Ring")
oEditor.type("Hello Ring and .NET")
? nl + "2. text: " + oEditor.text()
oEditor.undo()
? " undo : " + oEditor.text()
oEditor.undo()
? " undo : " + oEditor.text()
oEditor.redo()
? " redo : " + oEditor.text()
oEditor.type("Hello again")
? " a new change: " + oEditor.text() + " (can redo now? " + yesNo(oEditor.canRedo()) + ")"
# 3. A queue
oQueue = new StringQueue()
oQueue.Enqueue("print report")
oQueue.Enqueue("send email")
oQueue.Enqueue("backup files")
? nl + "3. jobs waiting: " + oQueue.Count
while oQueue.Count > 0
? " doing: " + oQueue.Dequeue()
end
# 4. Where stacks and queues are used: the Back button of a browser (stack), a printer (queue), a to-do order, a call stack
? nl + "4. The queue is empty now. Look at Count first, because Dequeue on an empty queue raises an error:"
try
oQueue.Dequeue()
catch
? " Dequeue on an empty queue raised an error: " + left(cCatchError,45)
done
func yesNo lValue
if lValue
return "yes"
ok
return "no"
# a text with undo and redo: two stacks of earlier texts
class TextHistory
cCurrent = ""
oUndo = ""
oRedo = ""
func init
oUndo = new StringStack()
oRedo = new StringStack()
return self
func type cNewText
oUndo.Push(cCurrent)
cCurrent = cNewText
oRedo.Clear() # a new change makes the old future impossible
func undo
if oUndo.Count = 0
return
ok
oRedo.Push(cCurrent)
cCurrent = oUndo.Pop()
func redo
if oRedo.Count = 0
return
ok
oUndo.Push(cCurrent)
cCurrent = oRedo.Pop()
func canRedo
return oRedo.Count > 0
func text
return cCurrent1. Peek (look at the top): c, Pop (take it): c, now 2 items, the top is b
2. text: Hello Ring and .NET
undo : Hello Ring
undo : Hello
redo : Hello Ring
a new change: Hello again (can redo now? no)
3. jobs waiting: 3
doing: print report
doing: send email
doing: backup files
4. The queue is empty now. Look at Count first, because Dequeue on an empty queue raises an error:
Dequeue on an empty queue raised an error: DotNet Error: System.InvalidOperationExceptioHow it works#
Undo and redo#
TextHistory keeps the current text and two stacks. Each change pushes the old text on the undo stack. undo pushes the current text on the redo stack and pops the previous text from the undo stack. redo does the reverse. The most recent change is always on top, which is exactly the order a user expects.
A new change after an undo clears the redo stack (Clear()): the old future no longer exists. The last line of step 2 shows can redo now? no.
The same idea works for a drawing program (push each shape), a browser (the Back and Forward buttons are two stacks), or a calculator (the operands).
The queue#
Step 3 adds three jobs and serves them in the order they came. A worker program often has a loop while queue.Count > 0 that takes the next job.
Empty collections#
Dequeue() or Pop() on an empty collection raises an error (the last lines of the output). Look at Count first, or wrap the call in try / catch (the tutorial When things go wrong).
What you learned#
- stacks and queues and when to use each,
- undo and redo with two stacks,
- always check
Count.
Exercises#
- Add a limit of 100 undo steps: when the undo stack is full, drop the oldest entry (hint: use a list).
- Make a job queue with priorities: urgent jobs first (hint: two queues).
- Check that parentheses in
(a + [b]) * care balanced, using a stack.