0% found this document useful (0 votes)
2 views

ceng2001_week3

This document discusses the concept of stacks as a linear data structure, detailing its operations such as push, pop, peek, isEmpty, and size. It explains the Last In First Out (LIFO) principle, applications in balancing parentheses, and converting decimal to binary. Additionally, it covers infix, prefix, and postfix notations, along with algorithms for converting between these forms and evaluating postfix expressions.

Uploaded by

canseverhicrann
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)
2 views

ceng2001_week3

This document discusses the concept of stacks as a linear data structure, detailing its operations such as push, pop, peek, isEmpty, and size. It explains the Last In First Out (LIFO) principle, applications in balancing parentheses, and converting decimal to binary. Additionally, it covers infix, prefix, and postfix notations, along with algorithms for converting between these forms and evaluating postfix expressions.

Uploaded by

canseverhicrann
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/ 46

Basic Data Structures - Stack

Data Structures and Algorithms


Week 3

Erdem Türk, PhD


Fall 2024
Linear Structure
• Linear structure is a data structure for holding
multiple items
– stacks, queues, deques, lists

• The items can be added in different ways, but


once added the retain a relation to their
neighbors' that does not change.
x b m z a d q
Linear Structures
• In other words once a item is added it stays in
that position relative to the other items that
came before it and came after it.

• Think of a line of cars in a line that follow the


rules that once in the line, they can not pass
another car to change places. and where they
can leave and join the line depends on the
rules of the particular data structure (list,
stack, queue, deque, ordered list, etc.)
Stack
pop (remove item to
push (add item to top)
top, and return it)

peek (return reference to


size(return number top item, but don't
of items in stack) remove it)≈

isEmpty ( return True if no items


on the stack, False otherwise
Stack() create a new empty
stack and return a reference to it
Last in first out = LIFO

good for reversing order


good for matching up nested structures ( ( ) ( ()() ) )
Stack ADT (abstract data type)
Stack() creates a new stack that is empty. It needs no
parameters and returns an empty stack.
push(item) adds a new item to the top of the stack. It
needs the item and returns nothing.
pop() removes the top item from the stack. It needs no
parameters and returns the item. The stack is modified.
peek() returns the top item from the stack but does not
remove it. It needs no parameters. The stack is not modified.
isEmpty() tests to see whether the stack is empty. It needs
no parameters and returns a boolean value.
size() returns the number of items on the stack. It needs
no parameters and returns an integer.
Stack Operation Stack Contents Return Value
s = Stack() []
s.isEmpty() [] TRUE
s.push(4) [4]
s.push('dog') [4,'dog']
s.peek() [4,'dog'] 'dog'
s.push(True) [4,'dog',True]
s.size() [4,'dog',True] 3
s.isEmpty() [4,'dog',True] FALSE
s.push(8.4) [4,'dog',True,8.4]
s.pop() [4,'dog',True] 8.4
s.pop() [4,'dog'] TRUE
s.size() [4,'dog'] 2

Note: top is on left


Implementation
• Using list with last item of list is top of stack

• Using list with first item on list is top of stack

• Note that the ability to change to a different


implementation without affecting the
operation of the ADT set of methods is the
essence of and abstract data type
Implementation
Implementation
Stack for balance parentheses
• (defun square(n) ( * n n ) ) – lisp language
creates square method
• lisp has a huge number of parentheses
• languages that use parentheses must use
them in a balanced way, also true for lots of
other computer language things
• { }, [ ], <tag> </tag>, < >
consider
• balanced?
(()()())
(((())))
(()((())()))

))))((((
()))
(()()(()
The program challenge
• write an algorithm that will read a string of
parentheses from left to right and decide
whether the symbols are balance.

Closing symbols ) match opening symbols ( in


the reverse order of their appearance.
function parChecker(s)
• Pseudocode:
create stack
for each symbol in string:
if ( then push it on stack
else
if stack is empty then return False
else pop stack
if done scanning and stack is empty
return true
else
return false
• Time complexity: 𝑂(𝑛)
• Space complexity: 𝑂(𝑛)
General balanced symbols
• Code to handle ( ), { }, and [ ]
• only need to push if we detect (, { or [
• and when we pop, verify that it matches its
opposite pair

• See code
• Time complexity: 𝑂(𝑛)
• Space complexity: 𝑂(𝑛)
Stack for converting decimal to binary
• Binary is especially important to CS and
programming since the computer stores
everything in binary one and zeros:
• 110101100011
• Hex is another base that is easier then binary
but each hex digit represents 4 bits
– Hex uses the digits 0123456789ABCDEF
• 1101 0110 0011 would be D63
Stack for converting decimal to binary
• The decimal number 23310 and its
corresponding binary equivalent 111010012
are interpreted respectively as

2×102+3×101+3×100
and
1×27+1×26+1×25+0×24+1×23+0×22+0×21+1×20
Easy divide by 2 and collect
Decimal: 233
remainders
20 digit

Binary: 11101001 27 digit


• Time complexity: 𝑂(log 𝑛)
• Space complexity: 𝑂(log 𝑛)
do any base
• if we want to convert to base 8 we can divide by 8
and get the remainder i % 8
• in a particular base, the modulus operator can
return the last digit of any number in that base:
digit = number % base
and then you can remove the last digit in that base by
dividing by the base
remaining = remaining // base

See code
• Time complexity: 𝑂(logb 𝑛)
• Space complexity: 𝑂(logb 𝑛)
inFix, prefix, postfix and
evaluation
infix
• when you write an expression
C*D
• you know form the form that you multiply the
value of variable C by the value in variable D
• This type of notation is know as infix since the
operator * is in between the two operators C
and D
more infix
• consider
B+C*D
• this is more complicated, which do you do
first, B + C or C * D
• Well you know because you have been doing
this that the order of precedence tells you
when what to do first. The only exception to
precedence is adding ( )
Fully Parenthesized
• If you add a pair of parentheses around every
operation in a way to indicate the order needed
B+C*D becomes (B+(C*D))

• When you do this, you don't need precedence


rules.
• This use one pair of ( ) per operator, if you have 4
operators, you will have 4 pairs of parentheses
prefix
• There are two other ways of writing
expressions you may have never heard before
• The first is prefix or also known as polish
notation invented by the great polish logician
Jan Lukasiewicz
• you write the operator before
the two operand, so A + B
becomes + A B
in prefix notation.
postfix, also called
Reverse polish notation (RPN)
• in prefix you put the operator after the two operands :
A + B becomes A B +
• RPN is very useful for computers
– You don’t need parentheses
– Always works from left to right

Infix prefix postfix


A+B +AB AB+
A+B*C +A*BC ABC*+
A*B–C/D -*AB/CD AB*CD/-
other examples
Infix prefix postfix
A+B*C+D ++A*BCD ABC*+D+
(A + B) * ( C + D) *+AB+CD AB+CD+*
A*B+C*D +*AB*CD AB*CD*+
A+B+C+D +++ABCD AB+C+D+

Note that the operands stay in their original order


Algorithm to convert infix to postfix
• when you fully parenthesize an expression
every pair of parentheses denotes two
operands with an operator in the middle

( A + ( B * C ) )

highest priority parentheses


Algorithm to convert infix to postfix
• when you fully parenthesize an expression
every pair of parentheses denotes two
operands with an operator in the middle

( A + ( B * C ) )
1 --------2--------

next priority of parentheses


Algorithm to convert infix to postfix
• when you fully parenthesize an expression
every pair of parentheses denotes two
operands with an operator in the middle

( A + ( B * C ) )

move operator to postfix position


Algorithm to convert infix to postfix
• when you fully parenthesize an expression
every pair of parentheses denotes two
operands with an operator in the middle

( A + ( B C * ) )
Algorithm to convert infix to postfix
• when you fully parenthesize an expression
every pair of parentheses denotes two
operands with an operator in the middle

( A + ( B C * ) )
1 --------2--------

move operator to postfix position


Algorithm to convert infix to postfix
• when you fully parenthesize an expression
every pair of parentheses denotes two
operands with an operator in the middle

( A ( B C * ) + )
1 --------2--------

remove all parentheses, we don't need them


Algorithm to convert infix to postfix
• when you fully parenthesize an expression
every pair of parentheses denotes two
operands with an operator in the middle

A B C * +
take out extra spaces:

A B C * +
• You do prefix by just moving operator to left,
but other wise it is the same:
The algorithm
• we will be evaluating converting a infix
expression (not fully parenthesized) to postfix
• We will design a function named
infixToPostfix( string parameter)
that return a new string expression in postfix.
The string expression must have a space
between every token of ( ) a number of
operator
Algorithm
• Consider
( A + B ) * C -> becomes A B + C *
when we see ( we know that what is in the () is high
precedence and can be done when we see the
matching ) pair -> A B +
• But for the expression A + B * C the result is:
A B C * +, we need to reverse the operators when
the precedence dictates it. since reversal is nicely
handled with a stack, that is what we will use
Algorithm

Converting A · B + C · D to Postfix Notation


Postfix evaluation if simple
• process from left to right, if the token is an
operand push it onto stack
• if the token is an operator, pop the two
operands off stack perform the operator on
them and then push the result back onto the
stack.
• when you run out of tokens, you should only
have one value on stack, just pop it and return
it
• You need to look at code for the post fix
evaluations on your own.
• It has a big problem, it only handles number
of one digit. Can you fix it?
• Does the converter from infix to postfix have
the same problem?

You might also like