3.4. The Stack Abstract Data Type

The stack abstract data type is defined by the following structure and operations. A stack is structured, as described above, as an ordered collection of items where items are added to and removed from the end called the “top.” Stacks are ordered LIFO. The stack operations are given below.

For example, if s is a stack that has been created and starts out empty, then Table 1 shows the results of a sequence of stack operations. Under stack contents, the top item is listed at the far right.

Table 1: Sample Stack Operations

Stack Operation

Stack Contents

Return Value

s.empty()

[]

1

s.push('horse')

['horse']

s.push('dog')

['horse','dog']

s.top()

['horse','dog']

'dog'

s.push('cat')

['horse','dog','cat']

s.size()

['horse','dog','cat']

3

s.empty()

['horse','dog','cat']

0

s.push('turtle')

['horse','dog','cat','turtle']

s.pop()

['horse','dog','cat']

s.pop()

['horse','dog']

s.size()

['horse','dog']

2

Before you keep reading...

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

You have attempted 1 of 2 activities on this page