You are on page 1of 21

DFC30233

Chapter 3 : Stacks

Objectives
Upon completion you will be able to

• Explain the design, use, and operation of a stack


• Implement a stack using a linked list structure

1
CHAP 3 : PART 1

2
3
 A stack is collection of data item arrange in sequence
arrangement.
 A stack has the LIFO (Last In First out) concept. The last
element to be added is the first to be removed
 Elements (node) are added to and removed from the top of
the stack (the most recently added items are at the top of the
stack).
 Parsing
 Evaluating postfix expression
 Discuss within a class and name a few example of stack application
………..

5
1. Create stack
2. Check empty stack
3. Check full stack
4. Push item to stack
5. Pop item from stack
 Stack is similar to array but its operation only can be done on
top of the item in the list.
 The two main operations applicable to a stack are:
 Push: an item is put on top of the stack, increasing the
stack size by one. As stack size is usually limited, this may
provoke a stack overflow if the maximum size is exceeded.
 Pop: the top item is taken from the stack, decreasing stack
size by one. In the case where there was no top item (i.e.
the stack was empty), a stack underflow occurs.
Operation in STACK
Stack overflow
 The condition resulting from trying to push an element onto
a full stack.
if(!stack.IsFull())
stack.Push(item);
Stack underflow
 The condition resulting from trying to pop an empty stack.
if(!stack.IsEmpty())
stack.Pop(item);
Basic Stack Operations : Push

10
 Function: Adds newItem to the top of the stack.
 Preconditions: Stack has been initialized and is not
full.
 Postconditions: newItem is at the top of the stack.
Basic Stack Operations : Pop

12
 Function: Removes topItem from stack and
returns it in item.
 Preconditions: Stack has been initialized and is not
empty.
 Postconditions: Top element has been removed
from stack and item is a copy of the removed
element.
Basic Stack Operations : Stack Top

14
 Create stack
 Let say, size = 4

3
2
1
0

top = -1

16
 Determine whether stack is full / not – before insert an item to stack
 If stack is Full -> insert operation cannot be done

3
2
1
0
top = 3
 Insert item into stack
 If stack ≠ full => proceed insert item

3
2
1
0

top = 12
30
-1
top
 Delete item from stack
 If stack ≠ empty => proceed delete item

3
2
1
0

top = -1
3
1
2
0
top
20
a) There is a stack size 4. Sketch diagram based on the statement below. Set a value
of the top equal to -1.

 CreateStack(s);
 Push(s,’K’);
 Push(s,’N’);
 Pop(s);
 Push(s,’M’);
 Push (s,’T’)
 Push (s,’J’)

a) Sketch diagram to show changes towards the stack for each operation below by
use linked list implementation.

 push 35, 45, 89, 33


 pop
 push 76,21,55
 pop

You might also like