FINALS CC4 Reviewer
FINALS CC4 Reviewer
Introduction to Stacks
A stack is a linear structure in which items are added or removed only at one end the top.
Homogenous
Stack user cannot have direct access to data items inside the stack
Can hold any number of data items (in principle), however, there is an upper limit to stack size depending on
the memory space
Stack ADT (Abstract Data Type) - A list with the restriction that insertion and deletion can be performed
only from one end, called the top.
Operations:
Push (x) – Insert or push some item “x” onto the stack.
Before this operation, the stack if often checked if it has enough capacity to accommodate the new item.
If stack is full, an overflow would occur
Pop( ) – Removing the most recent item or element from the stack.
Must ensure that the stack is not empty before this operation.
If stack contains no item, popping would cause an underflow error
Top( ) – Returns the copy of the item or element at the top of the stack. The item itself is not removed
from the stack. This operation is also called peek
IsEmpty( ) – It will return true if the stack is empty, false otherwise. Normally applied before the pop
operation to avoid stack underflow
IsFull()- – It will return true if the stack is full, false otherwise. Normally applied before the push operation
to avoid stack overflow. Not used when dynamic memory allocation is used
Create - generates an empty stack object and reserves necessary storage space
Destroy – removes all elements from the stack and releases memory allocated to stack
Algorithm of push()
The process of putting a new data element onto stack is known as a Push Operation. Push operation
involves a series of steps −
Step 1 − Checks if the stack is full.
finals cc4 1
Step 2 − If the stack is full, produces an error and exit.
Step 3 − If the stack is not full, increments top to point next empty space.
Step 4 − Adds data element to the stack location, where top is pointing.
Step 5 − Returns success.
Algorithm of pop()
Accessing the content while removing it from the stack, is known as a Pop Operation. In an array
implementation of pop() operation, the data element is not actually removed, instead top is decremented
to a lower position in the stack to point to the next value. But in linked-list implementation, pop() actually
removes data element and deallocates memory space.
Step 3 − If the stack is not empty, accesses the data element at which top is pointing.
Step 4 − Decreases the value of top by 1.
Step 5 − Returns success.
finals cc4 2
Array Implementation
The only important design decision to be made is which end of the array should represent the top of the
stack.
Inefficient implementation because now every push or pop operation will require that all elements
currently in the stack be shifted one position in the array, for a cost of Θ(n) if there are n elements.
as elements are pushed onto the stack, they are appended to the tail of the list.
Method pop removes the tail element. In this case, the cost for each push or pop operation is only Θ(1).
Size of array determines the maximum number of data elements in the stack
finals cc4 3
When an element is popped off, top is decremented by 1
If an application requires less space than the array size, storage space will be wasted
The program will crash if application requires more storage space at runtime
Linked-List Implementation
Elements are inserted and removed only from the head of the list.
A header node is not used because no special-case code is required for lists of zero or one elements.
The only data member is top, a pointer to the first (top) link node of the stack.
Method push first modifies the next field of the newly created link node to point to the top of the stack
and then sets top to point to the new link node.
Method pop is also quite simple. Variable temp stores the top nodes’ value, while ltemp links to the top
node as it is removed from the stack.
The stack is updated by setting top to point to the next link in the stack.
The old top node is then returned to free store (or the freelist), and the element value is returned
Push
finals cc4 4
Pop
Operations
removeBack(): returns and removes the element at the end of the list
removeFront(): returns and removes the element at the front of the list.
finals cc4 5
insertBack(x): inserts an element on the back of the list.
2. If tail is NULL, update head and tail to point to the new node; otherwise.
Stack Applications
Stacks are also used by Text editors, Web browsers and Application packages
Recursion Implementation
Perhaps the most common computer application that uses stacks is not even visible to its users. This is
the implementation of subroutine calls in most programming language runtime environments.
A subroutine call is normally implemented by placing necessary information about the subroutine
(including the return address, parameters, and local variables) onto a stack.
This information is called an activation record. Further subroutine calls add to the stack. Each return from
a subroutine pops the top activation record off the stack.
Recursion Implementation
Perhaps the most common computer application that uses stacks is not even visible to its users. This is
the implementation of subroutine calls in most programming language runtime environments.
A subroutine call is normally implemented by placing necessary information about the subroutine
(including the return address, parameters, and local variables) onto a stack.
This information is called an activation record. Further subroutine calls add to the stack. Each return from
a subroutine pops the top activation record off the stack.
Implementing recursion with a stack. β values indicate the address of the program instruction to return to
after completing the current function call. On each recursive function call to fact, both the return address
finals cc4 6
and the current value of n must be saved. Each return from fact pops the top activation record off the
stack.
Recursion Implementation
Here, we simply push successively smaller values of n onto the stack until the base case is reached,
then repeatedly pop off the stored values and multiply them into the result.
Parentheses are used in arithmetic expressions to specify priority of evaluation in a valid expression, ‘(‘
match with a corresponding ‘)’
The following expression has the same number of ‘)’ and ‘(‘ , but it is illegal.
finals cc4 7
We can use a stack to validate an expression using the following algorithm
5. If stack is not empty at the end of the scan, report mismatching error
Array scheme is suitable for stacks with fixed number of data items. Its implementation is simple.
In array implementation, all stack operations involve manipulating only the first element
Delete operation has time efficiency of O(N), because N nodes are deleted to release storage space
Advantages of Stacks
Helps manage the data in particular way (LIFO) which is not possible with Linked list and array.
When function is called the local variables are stored in stack and destroyed once returned. Stack is
used when variable is not used outside the function.
Stack frees you from the burden of remembering to cleanup(read delete) the object
Not easily corrupted (No one can easily inset data in middle)
Disadvantages of Stacks
finals cc4 8
Stack memory is limited.
Creating too many objects on the stack will increase the chances of stack overflow
Algebraic Expression
Operator is a symbol which signifies a mathematical or logical operation between the operands. Example
of familiar operators include +,-,*, /, ^
INFIX: the expressions in which operands surround theoperator, e.g. x+y, 6*3 etc this way of writing the
Expressions is called infix notation.
POSTFIX: Postfix notation are also Known as Reverse Polish Notation (RPN). They are different from
the infix and prefix notations in the sense that in the postfix notation, operator comes after the
operands, e.g. xy+, xyz+* etc.
PREFIX: Prefix notation also Known as Polish notation. In the prefix notation, operator comes before the
operands, e.g. +xy, *+xyz etc.
Tie Breaker
When an operand lies between two operators that have the same priority, the operand associates with
the operator on the left.
a + b – c // a * b / c / d
Delimeters
Sub expression within delimiters is treated as a single operand, independent from the remainder of the
expression.
(a + b) * (c – d) / (e – f)
Why?
1. Why use PREFIX and POSTFIX notations when we have simple INFIX notation?
2. INFIX notations are not as simple as they seem specially while evaluating them. To evaluate an infix
expression, we need to consider Operators’ Priority and Associative property
1. To solve this problem Precedence or Priority of the operators were defined. Operator precedence
governs evaluation order. An operator with higher precedence is applied before an operator with lower
precedence.
3.Postfix and prefix expression forms do not rely on operator priorities, a tie breaker, or delimiters.
4.Both prefix and postfix notations have an advantage over infix that while evaluating an expression in prefix or
postfix form we need not consider the Priority and Associative property (order of brackets).
E.g. x/y*z becomes /xyz in prefix and xy/z in postfix. Both prefix and postfix notations make Expression
Evaluation a lot easier.
finals cc4 9
5.So it is easier to evaluate expressions that are in these forms.
3.Expressions are evaluated from left to right. Precedence rules and parentheses are never needed!!
Postfix Examples
finals cc4 10
ii.If the top of stack is opening parenthesis, push operator on stack
iii.If it has higher priority than the top of stack, push operator on stack.
iv.Else pop the operator from the stack and output it, repeat step 4
5.If it is a closing parenthesis, pop operators from stack and output them until an opening parenthesis is
encountered. pop and discard the opening parenthesis.
6.If there is more input, go to step 1
1.Each operator in a postfix string refers to the previous two operands in the string.
2.Suppose that each time we read an operand we push it into a stack. When we reach an operator, its operands
will then be top two elements on the stack
3.We can then pop these two elements, perform the indicated operation on them, and push the result on the
stack.
4.So that it will be available for use as an operand of the next operator.
finals cc4 11
Evaluation a postfix notation
1.Use a stack to evaluate an expression in postfix notation.
Initialize result as a blank string, Iterate through given expression, one character at a time
i. If the operator’s precedence is greater than or equal to the precedence of the stack top of the operator stack,
then push the character to the operator stack.
finals cc4 12
ii. If the operator’s precedence is less than the precedence of the stack top of operator stack then “pop out an
operator from the stack and add it to the result until the stack is empty or operator’s precedence is greater
than or equal to the precedence of the stack top of operator stack“. then push the operator to stack.
3.If the character is “(“, then push it onto the operator stack.
4.If the character is “)”, then “pop out an operator from the stack and add it to the result until the corresponding “(“
is encountered in operator stack. Now just pop out the “(“.
A. Identify five (5) real time scenarios on how Stack Data Structures affect modern technologies and explain
how Stack Data Structures is being used in these modern technologies.
1. A + B * C + D
2. (A + B) * (C + D)
1. A B * C D * +
2. A B + C + D +
Queues
is a list-like structure that provides restricted access to its elements. Queue elements may only be
inserted at the back (called an enqueue operation)and removed from the front (called a dequeue
operation). Queues operate like standing in line at a movie theater ticket counter. They call a queue a
“FIFO” list, which stands for “First-In, First-Out.”
Feature/operations
No implementation details
In real world, a queue is a structure goes in first, comes out first or called FIFO.A stack which is call Last
in First Out Structure (LIFO)
In Queue, however an insertion must happen at one end that we call rear or tail of the queue and any
removal must happen at the other end called front or end of the queue
finals cc4 13
A List or collection with the restriction that insertion can be performed at one end (rear) and deletion can
be performed at the other end (front).
Operations:
Logically a Queue can be shown as a figure or container, open from two sides, so an element can be
inserted or enqueued from one side and can be remove or dequeued on the other side.
A Printer shared on a network. Any machine on the network can send print request on the printer but it
can only print one request at a time. When a request comes and the printer is busy, the printer will not
say that can’t you see I’m busy, what really happens is the program will put the request in a queue.
Queue Implementation
int A[10]
front <--1
rear <- -1
IsEmpty()
{
if front == -1 && rear == -1
return true
else
return false
}
finals cc4 14
Circular Array Queue
finals cc4 15