Stack Structure
Stack Structure
Email: [email protected]
Chapter 2
Stack Structure
Stack
Based on the everyday notion of a stack, such as a stack of books, or
a stack of plates.
• Definition
• A list of elements in which an element may be added (inserted) or
removed (deleted) only at one end, called the top of the stack.
• So, the last item pushed onto the stack is always the first that will
be popped from the stack. This property is called Last-In, FirstOut
(LIFO) or First-In-Last-Out (FILO)
Push & Pop
Stack
Stack Specification:
• A stack either empty or consists of two parts:
a top element
a stack(the remaining elements)
• The elements in the stack may be of any type but, all the elements in the given
stack must be the same type.
Preconditions:
• These are properties about the inputs that are assumed by an operation.
• Postconditions:
• Specify the effects of an operation. These are the only things you may assume
have been done by the operation. They are only guaranteed to hold if the
preconditions are satisfied.
Operations in Stack
• CreateStack
Inputs : none
Outputs: S (a stack)
Preconditions: none
Postconditions: S is defined (i.e. created) and empty (i.e. initialized to be empty)
• IsStackEmpty
• Inputs: S (a stack)
• Outputs: IsStackEmpty true or false
• Preconditions: The stack exists, and it has been initialized
• Postconditions: IsStackEmpty is true the S is empty.
Operations in Stack
• Pop
Inputs: S (a stack)
Outputs: S’ (i.e., S is changed) and T the element removed
Preconditions: S is not empty
Postconditions: The top of the stack has been removed and returned in T
• IsStackFull
Inputs: S (a stack)
Outputs: IsStackFull true or false
Preconditions: The stack exists, and it has been initialized
Postconditions: IsStackFull is true the S is full
Operations in Stack
• Push
Inputs: S (a stack) and V (a value)
Outputs: S‘ (i.e. S changed)
Preconditions: S is not full, and V is of appropriate type for an element of S
Postconditions: S’ has V as its top element and S as its remaining elements.
Note: S’ is the updated S
Implementation of Stack
Contiguous Implementation
In order to create a stack, we must import java.util.stack package and use the Stack()
constructor of this class. The below example creates an empty Stack.
Contiguous Implementation
Firstly, making sure the stack is empty
Contiguous Implementation
Then, adding values to the stack
Contiguous Implementation
45
95
20
15
Contiguous Implementation
Peek the last value of the stack with use of Peek function
Contiguous Implementation
Removing the last value of the stack and peek the last value next
Contiguous Implementation
Thank You