Smalltalk Stack Examples

Using an Array



Object subclass: #Stack
  instanceVariableNames: 
    'anArray top '
  classVariableNames: ''
  poolDictionaries: ''  !


!Stack class methods !
   
new
        | s |
    s := super new.
    s setsize: 10.
    ^s! !



!Stack methods !
  
pop
        | item |
    item := anArray at: top.
    top := top - 1.
    ^item!

printOn: aStream
    aStream nextPutAll: 'Stack['.
    1 to: top do: [:i | (anArray at: i) printOn: aStream.  aStream space].
    aStream nextPutAll: ']'!
   
push: item
    top := top + 1.
    anArray at: top put: item!
 
setsize: n
   anArray := Array new: n.
    top := 0! !

Using a Linked List



Object subclass: #LStack
  instanceVariableNames: 
    'list '
  classVariableNames: ''
  poolDictionaries: ''    !


!LStack class methods ! !



!LStack methods !
   
pop
        | item |
    list isNil ifTrue: [self error: 'trying to pop an empty stack'].
    item := list first.
    list := list rest.
    ^item!
   
printOn: aStream
    aStream nextPutAll: 'Stack['.
    list isNil ifFalse: [list reversePrint: aStream].
    aStream nextPutAll: ']'.!
   
push: item
    list := Link new first: item rest: list! !

This uses a helper class Link:

Object subclass: #Link
  instanceVariableNames: 
    'first rest '
  classVariableNames: ''
  poolDictionaries: ''    !


!Link class methods ! !



!Link methods !
   
first
    ^first!
  
first: f rest: r
    first := f.
    rest := r.!
  
rest
    ^rest!

reversePrint: aStream
    rest isNil ifFalse: [rest reversePrint: aStream].
    aStream space.
    first printOn: aStream.! !