0% found this document useful (0 votes)
33 views15 pages

FINALS CC4 Reviewer

A stack is a linear data structure that follows the LIFO (last-in, first-out) principle. Elements are only added or removed from one end called the top. Common stack operations include push, which adds an element to the top, pop, which removes the top element, and peek, which returns the top element without removing it. Stacks have numerous applications including implementing function calls, recursion, undo/redo features in software, and parsing expressions.

Uploaded by

Marc Joel Junio
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views15 pages

FINALS CC4 Reviewer

A stack is a linear data structure that follows the LIFO (last-in, first-out) principle. Elements are only added or removed from one end called the top. Common stack operations include push, which adds an element to the top, pop, which removes the top element, and peek, which returns the top element without removing it. Stacks have numerous applications including implementing function calls, recursion, undo/redo features in software, and parsing expressions.

Uploaded by

Marc Joel Junio
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

finals cc4

Introduction to Stacks

A stack is also known as a Last-In-First-Out (LIFO) list.

A stack is a linear structure in which items are added or removed only at one end the top.

The depth of stack is the number of elements it contains.

An empty stack has depth zero.

Homogenous

Elements are ordered

Stack user cannot have direct access to data items inside the stack

Only topmost item can be retrieved

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 1 − Checks if the stack is empty.


Step 2 − If the stack is empty, produces an error and exit.

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

simplified version of the array based list.

The only important design decision to be made is which end of the array should represent the top of the
stack.

One choice is to make the top be at position 0 in the array.

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).

An array of appropriate data type is used to store stack data

Size of array determines the maximum number of data elements in the stack

A variable top is used to identify the topmost element

The elements of stack are placed in a sequential order in the array

When an element is pushed onto stack, top is incremented by 1

finals cc4 3
When an element is popped off, top is decremented by 1

Disadvantages of Array Implementation of Stacks

Size of stack needs to be specified at compile time

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

1. Create a new node

2. Copy element to the new node

3. Link pointer of new node is set to point to pre-existing front node

4. Head pointer is re-set to point to the new node

finals cc4 4
Pop

1. Topmost element is copied for removal

2. A new pointer is created to point to front mode

3. Head pointer is reset to point to the next node

4. Using the new pointer, front node is deleted

Operations

insertFront(x): inserts an element on the front of the list

removeFront():returns and removes the element at the front of the list

insertBack(x): inserts an element on the back of the list

removeBack(): returns and removes the element at the end of the list

insertFront(x) : inserts an element on the front of the list.

1. Allocate a new node

2. Have new node point to old head

3. Update head to point to new node

removeFront(): returns and removes the element at the front of the list.

1. Update head to point to next node in the list.

2. Return element of previous head and delete the node.

finals cc4 5
insertBack(x): inserts an element on the back of the list.

1. Allocate a new node

2. If tail is NULL, update head and tail to point to the new node; otherwise.

Have the old tail point to the new node.

Update tail to point to new node.

Stack Applications

Stacks are extensively used in computer science and other disciplines

Stacks play a central role in the following situations

Translating and computing high-level computer languages

Implementing recursive procedures and recursive functions

Implementing search and traversal algorithms

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.

Reverse String Implementation

Using Stack for Parentheses Matching

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.

Using Stack for Parentheses Matching

finals cc4 7
We can use a stack to validate an expression using the following algorithm

1. Scan the expression from left to right

2. If ‘(‘ is encountered, push it onto the stack

3. If ‘)’ is found, pop the stack

4. If stack is empty, report a mismatched ‘)’

5. If stack is not empty at the end of the scan, report mismatching error

Performance of Stack Implementation

Array scheme is suitable for stacks with fixed number of data items. Its implementation is simple.

By contrast, the linked list implementation is complex but flexible

It involves creation and deletion of front node

It is preferable when size is unpredictable

In both implementations, amount of storage space is proportional to number of elements

In Big-Oh notation, space efficiency of either implementation is O(N)

In array implementation, all stack operations involve manipulating only the first element

It is independent of the number of elements in the array

Time efficiency is O(1)

List-based implementation also involves manipulating a single node at the front

It is independent of the number of nodes thus time efficiency is O(1)

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.

It gives control over how memory is allocated and deallocated.

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

Random access not possible

Algebraic Expression

An algebraic expression is a legal combination of operands and the operators.

Operand is the quantity (unit of data) on which a mathematical operation is performed.

Operand may be a variable like x, y, z or a constant like 5, 4,0,9,1 etc.

Operator is a symbol which signifies a mathematical or logical operation between the operands. Example
of familiar operators include +,-,*, /, ^

An example of expression as x+y*z.

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

E.g. expression 3+5*4 evaluate to 32 i.e. (3+5)*4 or to 23 i.e. 3+(5*4).

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.

Infix Expression is Hard To Parse

1.Need operator priorities, tie breaker, and delimiters.

2.This makes computer evaluation more difficult than is necessary.

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.

Examples of infix to prefix and postfix

Examples of infix to prefix and postfix

1.Postfix notation is another way of writing arithmetic expression.


2.In postfix notation, the operator is written after the two operands.

infix: 2+5 postfix: 2 5 +

3.Expressions are evaluated from left to right. Precedence rules and parentheses are never needed!!

Suppose that we would like to rewrite A+B*C in postfix

Applying the rules of precedence, we obtained.

Postfix Examples

Algorithm for Infix to Postfix


1.Examine the next element in the input.

2.If it is operand, output it.

3.If it is opening parenthesis, push it on stack.


4.If it is an operator, then

i.If stack is empty, push operator on stack.

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

7.If there is no more input, pop the remaining operators to output.

Suppose we want to convert 2*3/(2-1)+5*3 into Postfix form

Evaluation a postfix expression

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.

2.The postfix expression to be evaluated is scanned from left to right.

3.Variables or constants are pushed onto the stack.


4.When an operator is encountered, the indicated action is performed using the top elements of the stack,
and the result replaces the operands on the stack.

Evaluating a postfix expression

1. Initialize an empty stack

2. While token remain in the input stream


Read next token
If token is a number, push it into the stack
Else, if token is an operator, pop top two tokens off the stack, apply the operator, and push the answer
back into the stack

3. Pop the answer off the stack.

Question: Evaluate the following expression in postfix : 623+-382/+*2^3+

Initialize result as a blank string, Iterate through given expression, one character at a time

1. If the character is an operand, add it to the result.

2. If the character is an operator.

If the operator stack is empty then push it to the operator stack.

Else If the operator stack is not empty,

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 “(“.

Activity for review

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.

B. Convert the following Infix Expressions into Postfix Expressions

1. A + B * C + D

2. (A + B) * (C + D)

C. Revert the following Postfix Expressions to Infix Expressions

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.”

Queue ADT (Abstract Data Structure)

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

Queue ADT and Operations

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:

Enqueue(x), DeQueue(), Front(), IsEmpty

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.

Example: Queue of Integers


Create a Queue of integers
Initially an empty Queue
Enqueue number 2
Enqueue number 5
Enqueue number 3
Dequeue()

Example 2: Printer on a network

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

Linked List Implementation: Queue

finals cc4 15

You might also like