0% found this document useful (0 votes)
22 views56 pages

Lecture 4 Stack

Uploaded by

aro534721
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)
22 views56 pages

Lecture 4 Stack

Uploaded by

aro534721
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/ 56

Data Structures (CS212T)

Stacks

9/26/2024 https://www.pnu.edu.sa
Updated By L.Fatimah Alanizi 1
Outline

• Abstract data types


• Stacks
• Stack applications

9/26/2024 Updated By L.Fatimah Alanizi


2
Abstract data types (ADTs)
• Abstraction? Anything that hides details & provides only the essentials
• Abstract Data Types (ADTs): Simple data type or structured data type
with a set of operations whose implementation details are hidden

• Abstract data type (ADT): A specification of a collection of


data and the operations that can be performed on it.
• Describes what a collection does, not how it does it

We don't know exactly how a stack or queue is implemented, and we don't need to. We
just need to understand the idea of the collection and what operations it can perform.

9/26/2024 Updated By L.Fatimah Alanizi 3


Abstract data types (ADTs)
• ADTs specification:
• Answers the ‘what’ questions.
• Specification is written first.
• Users of an ADT need only know the specification, No implementation details

• ADTs implementation:
• Answers the ‘how’ questions.
• Done after specification
• Programmer (Implementer) who implements ADT is concerned with
specification, representation, implementation

9/26/2024 Updated By L.Fatimah Alanizi 4


Abstract Data Types (ADTs)
• Abstract Data Types (ADTs) is an abstraction of a data structure.

• An ADT specifies:
• Data stored
• Operations on the data
• Error conditions associated with operations -> OK

While designing ADTs, designer have to specify ADT’s data and operations
(before you implement them) , a designer has to deal with two types of questions :

1. Ask questions about the data in the data collection of the ADT ,what data type to be used?
(To decide the data structures )

2. What operations can be performed on the values of that particular data type?
9/26/2024 Updated By L.Fatimah Alanizi 5
Abstract Data Types (ADTs)
• Example: Design an ADT modeling a simple stock trading system

• The data stored are:


• buy/sell orders

• The operations supported are:


• order buy(stock, shares, price)
• order sell(stock, shares, price)
• void cancel(order)

• Error conditions:
• Buy/sell a nonexistent stock
• cancel a nonexistent order
9/26/2024 Updated By L.Fatimah Alanizi 6
Stacks

9/26/2024 Updated By L.Fatimah Alanizi 7


Stacks
• stack: A collection based on the principle of adding
elements and retrieving them in the opposite order.
• Last-In, First-Out ("LIFO")
• Elements are stored in order of insertion.
• We do not think of them as having indexes. push pop, peek
• Client(user) can only add/remove/examine
the last element added (the "top").
• Basic stack operations: top 3
• push: Add an element to the top. 2
• pop: Remove the top element. bottom 1

9/26/2024
• Top(peek): Examine the top element.
Updated By L.Fatimah Alanizi
stack
8
The Stack ADT
• The Stack ADT stores arbitrary objects (elements are of a generic type <E>)
• Insertions and deletions follow the last-in first-out scheme
• Think of a spring-loaded plate dispenser
• Structure: the elements are linearly arranged, and ordered according to the
order of arrival, most recently arrived element is called top
• Main (Core) stack operations:
• push(object): inserts an element
• object pop(): removes and returns the last inserted element

• Auxiliary stack operations:


• object top(): returns the last inserted element without removing it
• integer size(): returns the number of elements stored
• boolean isEmpty(): indicates whether
9/26/2024 no elements
Updated By L.Fatimah Alanizi are stored 9
Stack Interface in Java

• Java interface corresponding public interface Stack<E> {


to our Stack ADT public int size();
• Requires the definition of
public boolean isEmpty();
class EmptyStackException
• Different from the built-in public E top()
throws EmptyStackException;
Java class java.util.Stack
public void push(E e);
public E pop()
throws EmptyStackException;
}
10
9/26/2024 Updated By L.Fatimah Alanizi
Stack Interface in Java

11
9/26/2024 Updated By L.Fatimah Alanizi
Exceptions
• Attempting the execution of an operation of ADT may sometimes cause an
error condition, called an exception

• Exceptions are said to be “thrown” by an operation that cannot be


executed

• In the Stack ADT:


• operations pop and top cannot be performed if the stack is empty

• Attempting the execution of pop or top on an empty stack throws


an EmptyStackException
12

9/26/2024 Updated By L.Fatimah Alanizi


Stack implementations
1- Using Built in Stack Class in Java 2- Creating Stack Class based on Our Stack
ADT
• bulit in (ready to use) Stack Class in
java • You Have to implement your class by yourself
based on our previous ADT
• You can use it by importing
java.util.Stack and creating your • In This case you have to built the calss from
objects directly without creating a scartch
specific class for it • No use of any built in classes
• All the ADT Operations has been • You have to use the same name of ADT
implemented in the above built in class methods /operations)
(with a differenc of the name of some • There are two ways to implement it:
methodes/operations compared to our
ADT) A. Using Array (Array_based Stack)
B. Using Linked List (Linked List_based Stack)
9/26/2024 Updated By L.Fatimah Alanizi 13
Class Stack
Comparison between Our Stack ADT and Built in
Stack in Java
Our Stack ADT Class java.util.Stack

StackClassName<E>() constructs a new stack with elements of type E


push(value) push(value) places given value on top of stack
pop() pop() removes top value from stack and returns it;
throws EmptyStackException if stack is empty
top() peek() returns top value from stack without removing it;
throws EmptyStackException if stack is empty
size() size() returns number of elements in stack
isEmpty() empty() returns true if stack has no elements

Stack<String> s = new Stack<String>();


s.push("a");
s.push("b");
s.push("c");// bottom ["a", "b", "c"] top

System.out.println(s.pop()); // "c"
9/26/2024 Updated By L.Fatimah Alanizi 14
Stack Operation: Example

9/26/2024 Updated By L.Fatimah Alanizi 15


Array-based Stack Implementation

• A simple way of implementing the Stack ADT uses an array

• We add elements from left to right


• A variable keeps track of the index of the top element


S
0 1 2 t

16
9/26/2024 Updated By L.Fatimah Alanizi
Array-based Implementation

9/26/2024 Updated By L.Fatimah Alanizi 17


Array-based Stack Implementation

9/26/2024 Updated By L.Fatimah Alanizi 18


Array-based Stack Implementation
• The array storing the stack elements may become full
(due to Array fixed size)

• A push operation will then throw a FullStackException


• Limitation of the array-based implementation
• Not intrinsic to the Stack ADT


S
0 1 2 t isFull

9/26/2024 Updated By L.Fatimah Alanizi


19
Array-based Stack Implementation

// another pop code if deallocate array element is not considered


public E pop( )
{
if (isEmpty()) return null;
E e = data [ t-- ];
return e ;
}

9/26/2024 Updated By L.Fatimah Alanizi 20


Example: push(e)/pop()

public void push( E e ) { Length=5

if (size() == data.length) return;


data[ ++t ] = e; } 4

public E pop () { 2

if(isEmpty()) return null; 1

E e= data[ t-- ]; 0
return e }
T

9/26/2024 Updated By L.Fatimah Alanizi 21


Example: push(e)/pop()

public void push( E e ) { Length=5

if (size() == data.length) return;


data[ ++t ] = e; } 4

public E pop () { 2

if(isEmpty()) return null; 1

E e= data[ t-- ]; 0 T
return e }

9/26/2024 Updated By L.Fatimah Alanizi 22


Example: push(e)/pop()

public void push( E e ) { Length=5

if (size() == data.length) return;


data[ ++t ] = e; } 4

public E pop () { 2

if(isEmpty()) return null; 1

E e= data[ t-- ]; 0 T
return e }
e

9/26/2024 Updated By L.Fatimah Alanizi 23


Example: push(e)/pop()

public void push( E e ) { Length=5

if (size() == data.length) return;


data[ ++t ] = e; } 4

public E pop () { 2

if(isEmpty()) return null; 1

E e= data[ t-- ]; 0 T
return e }

9/26/2024 Updated By L.Fatimah Alanizi 24


Example: push(e)/pop()

public void push( E e ) { Length=5

if (size() == data.length) return;


data[ ++t ] = e; } 4

public E pop () { 2

if(isEmpty()) return null; 1 T


E e= data[ t-- ]; 0
return e }

9/26/2024 Updated By L.Fatimah Alanizi 25


Example: push(e)/pop()

public void push( E e ) { Length=5

if (size() == data.length) return;


data[ ++t ] = e; } 4

public E pop () { 2

if(isEmpty()) return null; 1 T


E e= data[ t-- ]; 0
e
return e }

9/26/2024 Updated By L.Fatimah Alanizi 26


Example: push(e)/pop()

public void push( E e ) { Length=5

if (size() == data.length) return;


data[ ++t ] = e; } 4

public E pop () { 2

if(isEmpty()) return null; 1 T


E e= data[ t-- ]; 0
return e; }

9/26/2024 Updated By L.Fatimah Alanizi 27


Example: push(e)/pop()

public void push( E e ) { Length=5

if (size() == data.length) return;


data[ ++t ] = e; } 4

public E pop () { 2

if(isEmpty()) return null; 1 T


E e= data[ t-- ]; 0
e
return e; }

9/26/2024 Updated By L.Fatimah Alanizi 28


Example: push(e)/pop()

public void push( E e ) { Length=5

if (size() == data.length) return;


data[ ++t ] = e; } 4

public E pop () { 2

if(isEmpty()) return null; 1

E e= data[ t-- ]; 0 T
e
return e; }

9/26/2024 Updated By L.Fatimah Alanizi 29


Example: push(e)/pop()

public void push( E e ) { Length=5

if (size() == data.length) return;


data[ ++t ] = e; } 4

public E pop () { 2

if(isEmpty()) return null; 1

E e= data[ t-- ]; 0 T
return e; }

9/26/2024 Updated By L.Fatimah Alanizi 30


Example: push(e)/pop()

public void push( E e ) { Length=5

if (size() == data.length) return;


data[ ++t ] = e; } 4

public E pop () { 2

if(isEmpty()) return null; 1

E e= data[ t-- ]; 0 T
return e; }
e

9/26/2024 Updated By L.Fatimah Alanizi 31


Example: push(e)/pop()

public void push( E e ) { Length=5

if (size() == data.length) return;


data[ ++t ] = e; } 4

public E pop () { 2

if(isEmpty()) return null; 1

E e= data[ t-- ]; 0
return e; }
T

9/26/2024 Updated By L.Fatimah Alanizi 32


Example: push(e)/pop()

public void push( E e ) { Length=5

if (size() == data.length) return;


data[ ++t ] = e; } 4

public E pop () { 2

if(isEmpty()) return null; 1

E e= data[ t-- ]; 0
return e; }
T

9/26/2024 Updated By L.Fatimah Alanizi 33


Array-based Implementation of the Stack
interface.

9/26/2024 Updated By L.Fatimah Alanizi 34


Sample Usage of ArrayStack Class

9/26/2024 Updated By L.Fatimah Alanizi 35


Performance and Limitations
• Performance
• Let n be the number of elements in the stack
• The space used is O(n)
• Each operation runs in time O(1)
• Limitations
• The maximum size of the stack must be defined a priori and cannot be
changed.
• Trying to push a new element into a full stack causes an implementation-
specific exception—Overflow.

36
9/26/2024 Updated By L.Fatimah Alanizi
Linked List-based Stack implementation
(1/2)
• The top of the stack is the head of the linked list.

• An instance variable keeps the current number of


elements.(size)

• push: create a new node and add it at the top (head) of the
stack.

• Pop: delete the node at the top (head) of the stack.

Top Bottom

37

9/26/2024 Sydney Rome Seattle New York


Updated By L.Fatimah Alanizi
Linked List-based Stack (2/2)
The Adapter Pattern

9/26/2024 Updated By L.Fatimah Alanizi 38


Can you Print a Stack without destroying it?
How?

9/26/2024 Updated By L.Fatimah Alanizi 39


Reversing an Array Using a Stack
buffer 9
3

a 2 2 a
0 1 2 3 0 1 2 3

3 5 2 9 5 9 2 5 3
1

0 3

9/26/2024 Updated By L.Fatimah Alanizi 40


Reversing an Array Using a Stack

9/26/2024 Updated By L.Fatimah Alanizi 41


STACK APPLICATIONS

9/26/2024 42 Updated By L.Fatimah Alanizi


Applications of Stacks
• Programming languages and compilers:
• method calls are placed onto a stack method3
return var
local vars
parameters

(call=push, return=pop) return var


method2 local vars
• compilers use stacks to evaluate Arithmatic expressions parameters

return var

• Matching up related pairs of things: method1 local vars


Parameters

• find out whether a string is a palindrome


• examine a file to see if its braces {([]) } match
• convert "infix" expressions to pre/postfix
• Sophisticated algorithms:
• searching through a maze with "backtracking“(Every time you reach a
dead-end, you backtrack to try another path until you find the exit or all path have been explored )

• many programs use an "undo


9/26/2024 stack"
Updated By of previous operations
L.Fatimah Alanizi 43
Applications of Stacks
• Direct applications
• Page-visited history in a Web browser
• Undo sequence in a text editor
• Chain of method calls in the Java Virtual Machine
• Indirect applications
• Auxiliary data structure for algorithms
• Component of other data structures

44
9/26/2024 Updated By L.Fatimah Alanizi
Parentheses Matching
❑Each “(”, “{”, or “[” must be paired with a matching
“)”, “}”, or “[”
• correct: ( )(( )){([( )])}
• correct: (( )(( )){([( )])})
• incorrect: )(( )){([( )])}
• incorrect: ({[ ])}
• incorrect: (

9/26/2024 Updated By L.Fatimah Alanizi 45


Parentheses Matching Algorithm
Algorithm ParenMatch
{ Input: An array X of n elements, each of which is either a grouping symbol, a variable, an arithmetic operator, or a number
Output: true if and only if all the grouping symbols in X match
Let S be an empty stack;
{()} case 1 – matching
for ( i=0; i < n; i++)
{() case 2 – more opening
if ( X[i] is an opening grouping symbol ) ()} case 3 – more closing
S.push( X[i] ); ({)} case 4 – not matching
else if ( X[i] is a closing grouping symbol )
{
if ( S.isEmpty() ) case 3
return false; // nothing to match with
if ( S.pop() does not match the type of X[i] ) case 4
return false; // wrong type
}
if ( S.isEmpty() ) case 1
return true; // every symbol matched
else case 2 46
return false; // some symbols were never matched
9/26/2024 Updated By L.Fatimah Alanizi
}
Parentheses Matching Algorithm

47
9/26/2024 Updated By L.Fatimah Alanizi
Parentheses Matching Algorithm

48
9/26/2024 Updated By L.Fatimah Alanizi
HTML Tag Matching
◼ For fully-correct HTML, each <name> should pair with a matching </name>
<body>
<center>
<h1> The Little Boat </h1> The Little Boat
</center>
The storm tossed the little boat
<p> The storm tossed the little
like a cheap sneaker in an old
boat like a cheap sneaker in an washing machine. The three
old washing machine. The three drunken fishermen were used to
drunken fishermen were used to such treatment, of course, but not
such treatment, of course, but the tree salesman, who even as
not the tree salesman, who even as a stowaway now felt that he had
a stowaway now felt that he overpaid for the voyage.
had overpaid for the voyage. </p>
<ol> 1. Will the salesman die?
<li> Will the salesman die? </li> 2. What color is the boat?
3. And what about Naomi?
<li> What color is the boat? </li>
<li> And what about Naomi? </li>
49
</ol>
9/26/2024 </body> Updated By L.Fatimah Alanizi
Exercises
• What are the differences between Array-based stack and Linked list-based stack?
• Array Based Stack has a fixed size, needed an additional exception for inserting
method(push),
• Write a generic method that called reverseStack which reverses the elements in a
stack with objects of type E, using another Stacks?

9/26/2024 Updated By L.Fatimah Alanizi 50


Exercises

• Write a method called search that finds out whether an element is on


the stack by returning its position? The element at the top of the
stack is at position 1. Position 2 is next and so on. If the requested
element is not found on the stack, -1 is returned.

9/26/2024 Updated By L.Fatimah Alanizi 51


public int FindEPosition( E key)
{
if (isEmpty()) return -1;

LLstack<E> temp = new LLstack<>();


int count=0, position=-1;

while (! isEmpty() )
{
count++;
E e=pop();

if (e.equals(key))
position=count;
temp.push(e);
}
while (!temp.isEmpty())
this.push(temp.pop());

return position;
9/26/2024 } Updated By L.Fatimah Alanizi 52
9/26/2024 Updated By L.Fatimah Alanizi 53
Excercises
• write a java code method that prints all the numbers greater than 10 in the
stack S
Public void Print_grater ( Stack <Integer> s) {
If ( ! s.isEmpty() ) {
Stack s2=new <int> stack();
int element;
while (!s.isEmpty()) {
element=s.pop();
if(element >10)
System.out.println(element);
s2.push(element);
}
while (!s2.isEmpty())
s.push(s2.pop());
} }
9/26/2024 Updated By L.Fatimah Alanizi 54
Exsercise
• What values are returned during the following series of stack operations, if executed upon an
initially empty stack?
push(5)
push(3)
pop()
push(2)
push(8)
pop()
pop() 3->8->2->1->6->7->4->9
push(9)
push(1)
pop()
push(7)
push(6)
pop()
pop()
push(4)
pop()
9/26/2024 pop() Updated By L.Fatimah Alanizi 55
References

1. Chapter 5, Data Structures and Algorithms by


Goodrich and Tamassia.

56

9/26/2024 Updated By L.Fatimah Alanizi

You might also like