SlideShare ist ein Scribd-Unternehmen logo
1 von 19
Data Structures and Algorithms in Java 1/19
2. Stack and Queue
Part 1: Stack
Data Structures and Algorithms in Java 2/19
Stack
Objectives
• Stacks
• Array-based stack
• Stack implemented by a singly linked list
• Stack class in java.util
Data Structures and Algorithms in Java 3/19
What is a stack?
3
• A stack is a linear data structure that can be accessed
only at one of its ends for storing and retrieving data
• A stack is a Last In, First Out (LIFO) data structure
• Anything added to the stack goes on the “top” of the
stack
• Anything removed from the stack is taken from the
“top” of the stack
• Things are removed in the reverse order from that in
which they were inserted
Data Structures and Algorithms in Java 4/19
Operations on a stack
4 • The following operations are needed to properly manage a
stack:
– clear() — Clear the stack
– isEmpty() — Check to see if the stack is empty
– push(el) — Put the element el on the top of the stack
– pop() — Take the topmost element from the stack
– top() — Return the topmost element in the stack without
removing it
Operations on a stack
Data Structures and Algorithms in Java 5/19
Stack Exceptions
5 • 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 StackEmptyException.
Data Structures and Algorithms in Java 6/19
Applications of Stacks
• Stacks are used for:
– Any sort of nesting (such as parentheses)
– Evaluating arithmetic expressions (and other sorts of
expression)
– Implementing function or method calls
– Keeping track of previous choices (as in backtracking)
– Keeping track of choices yet to be made (as in creating a
maze)
– Undo sequence in a text editor.
– Auxiliary data structure for algorithms
– Component of other data structures
Data Structures and Algorithms in Java 7/19
Stack in computer memory
• How does a stack in memory actually work?
– Each time a method is called, an activation record (AR) is allocated
for it. This record usually contains the following information:
• Parameters and local variables used in the called method.
• A dynamic link, which is a pointer to the caller's activation record.
• Return address to resume control by the caller, the address of the caller’s
instruction immediately following the call.
• Return value for a method not declared as void. Because the size of the
activation record may vary from one call to another, the returned value is placed
right above the activation record of the caller.
– Each new activation record is placed on the top of the run-time stack
– When a method terminates, its activation record is removed from
the top of the run-time stack
– Thus, the first AR placed onto the stack is the last one removed
AR is also called Stack frame
Data Structures and Algorithms in Java 8/19
Array-based Stack - 1
• A simple way of implementing the Stack ADT
(abstract data type) uses an array
• We add elements from left to right
• A variable top keeps track of the index of the
top element
S
0 1 2 top
…
Array-based stack
Data Structures and Algorithms in Java 9/19
• The array storing the stack elements
may become full
• A push operation will then throw a
FullStackException
– Limitation of the array-based
implementation
– Not intrinsic to the Stack ADT
S
0 1 2 top
…
Array-based Stack - 2
Array-based stack may become full
Data Structures and Algorithms in Java 10/19
Array implementation of a stack
10
class ArrayStack
{protected Object [] a; int top, max;
public ArrayStack()
{ this(50);
}
public ArrayStack(int max1)
{ max = max1;
a = new Object[max];
top = -1;
}
protected boolean grow()
{ int max1 = max + max/2;
Object [] a1 = new Object[max1];
if(a1 == null) return(false);
for(int i =0; i<=top; i++) a1[i] = a[i];
a = a1;
return(true);
}
public boolean isEmpty()
{ return(top==-1);}
public boolean isEmpty()
{ return(top==-1);}
public boolean isFull()
{ return(top==max-1);}
public void clear()
{ top=-1;}
public void push(Object x)
{ if(isFull() && !grow()) return;
a[++top] = x;
}
Object top() throws EmptyStackException
{ if(isEmpty()) throw new EmptyStackException();
return(a[top]);
}
public Object pop() throws EmptyStackException
{ if(isEmpty()) throw new EmptyStackException();
Object x = a[top];
top--;
return(x);
}
Data Structures and Algorithms in Java 11/19
Linked implementation of a stack
11
class Node
{ public Object info;
public Node next;
public Node(Object x, Node p)
{ info=x; next=p; }
public Node(Object x)
{ this(x,null); }
};
class LinkedStack
{ protected Node head;
public LinkedStack()
{ head = null; }
public boolean isEmpty()
{ return(head==null);}
public void push(Object x)
{ head = new Node(x,head);
}
Object top() throws EmptyStackException
{ if(isEmpty()) throw new EmptyStackException();
return(head.info);
}
public Object pop() throws EmptyStackException
{ if(isEmpty()) throw new EmptyStackException();
Object x = head.info;
head=head.next;
return(x);
}
Data Structures and Algorithms in Java 12/19
Implementing a stack using
ArrayList & LinkedList classes in Java
12
import java.util.*;
class MyStack
{ArrayList h;
MyStack() {h = new ArrayList();}
boolean isEmpty()
{return(h.isEmpty());}
void push(Object x)
{h.add(x);
}
Object pop()
{if(isEmpty()) return(null);
return(h.remove(h.size()-1));
}
}
import java.util.*;
class MyStack
{LinkedList h;
MyStack() {h = new LinkedList();}
boolean isEmpty()
{return(h.isEmpty());}
void push(Object x)
{h.add(x);
}
Object pop()
{if(isEmpty()) return(null);
return(h.removeLast());
}
}
Data Structures and Algorithms in Java 13/19
Convert decimal integer number to binary
number using a stack
13
public class Main
{public static void decToBin(int k)
{MyStack s = new MyStack();
System.out.print(k + " in binary system is: ");
while(k>0)
{s.push(new Integer(k%2));
k = k/2;
}
while(!s.isEmpty())
System.out.print(s.pop());
System.out.println();
}
public static void main(String [] args)
{decToBin(11);
System.out.println();
}
}
Data Structures and Algorithms in Java 14/19
Validate expression using stack - 1
14
We consider arithmetic expressions that may contain various pairs of grouping
symbols, such as
• Parentheses: “(” and “)”
• Braces: “{” and “}”
• Brackets: “[” and “]”
Each opening symbol must match its corresponding closing symbol. For example,
a left bracket, “[,” must match a corresponding right bracket, “],” as in the following
expression
[(5+x)−(y+z)].
The following examples further illustrate this concept:
• Correct: ( )(( )){([( )])}
• Correct: ((( )(( )){([( )])}))
• Incorrect: )(( )){([( )])}
• Incorrect: ({[ ])}
• Incorrect: (
We leave the precise definition of a matching group of symbols to Exercise R-6.6.
Data Structures and Algorithms in Java 15/19
Validate expression using stack - 2
15
An Algorithm for Matching Delimiters:
An important task when processing arithmetic expressions is to
make sure their delimiting symbols match up correctly. We can use
a stack to perform this task with a single left-to-right scan of the
original string.
Each time we encounter an opening symbol, we push that symbol
onto the
stack, and each time we encounter a closing symbol, we pop a
symbol from the stack (assuming it is not empty) and check that
these two symbols form a valid pair. If we reach the end of the
expression and the stack is empty, then the original expression was
properly matched. Otherwise, there must be an opening delimiter
on the stack without a matching symbol. If the length of the original
expression is n, the algorithm will make at most n calls to push and
n calls to pop.
Data Structures and Algorithms in Java 16/19
Matching Parentheses and HTML Tags
16
Another application of matching delimiters is in the validation of
markup languages such as HTML or XML. HTML is the standard
format for hyperlinked documents on the Internet and XML is an
extensible markup language used for a variety of structured data
sets.
In an HTML document, portions of text are delimited by HTML tags.
A simple opening HTML tag has the form “<name>” and the
corresponding closing tag has the form “</name>”. For example,
the <body> tag has the matching </body> tag at the close of that
document.
Ideally, an HTML document should have matching tags, although
most browsers tolerate a certain number of mismatching tags. We
can use stack to check whether an HTML document is valid or not.
Data Structures and Algorithms in Java 17/19
Stack class in Java
A Stack class implemented in the java.util package is an
extension of class Vector to which one constructor and five
methods are added.
Stack class in Java
Data Structures and Algorithms in Java 18/19
Summary
18
• A stack is a linear data structure that can be
accessed at only one of its ends for storing and
retrieving data.
• A stack is called an LIFO structure: last in/first
out.
Data Structures and Algorithms in Java 19/19
Reading at home
Text book: Data Structures and Algorithms in Java.
• 6 Stacks, Queues, and Deques 225
• 6.1 Stacks - 226

Weitere ähnliche Inhalte

Was ist angesagt?

Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template LibraryGauravPatil318
 
Introduction of data structure
Introduction of data structureIntroduction of data structure
Introduction of data structureeShikshak
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsHoang Nguyen
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocationMoniruzzaman _
 
Collections in .net technology (2160711)
Collections in .net technology (2160711)Collections in .net technology (2160711)
Collections in .net technology (2160711)Janki Shah
 
Data Structure and its Fundamentals
Data Structure and its FundamentalsData Structure and its Fundamentals
Data Structure and its FundamentalsHitesh Mohapatra
 
Analysis of algorithms
Analysis of algorithmsAnalysis of algorithms
Analysis of algorithmsiqbalphy1
 
Lecture11 standard template-library
Lecture11 standard template-libraryLecture11 standard template-library
Lecture11 standard template-libraryHariz Mustafa
 
On Applying Or-Parallelism and Tabling to Logic Programs
On Applying Or-Parallelism and Tabling to Logic ProgramsOn Applying Or-Parallelism and Tabling to Logic Programs
On Applying Or-Parallelism and Tabling to Logic ProgramsLino Possamai
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsJulie Iskander
 
XQuery Triggers in Native XML Database Sedna
XQuery Triggers in Native XML Database SednaXQuery Triggers in Native XML Database Sedna
XQuery Triggers in Native XML Database Sednamaria.grineva
 

Was ist angesagt? (20)

Searching Algorithms
Searching AlgorithmsSearching Algorithms
Searching Algorithms
 
Data structure
Data structureData structure
Data structure
 
LectureNotes-06-DSA
LectureNotes-06-DSALectureNotes-06-DSA
LectureNotes-06-DSA
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
 
LectureNotes-03-DSA
LectureNotes-03-DSALectureNotes-03-DSA
LectureNotes-03-DSA
 
Introduction of data structure
Introduction of data structureIntroduction of data structure
Introduction of data structure
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Collections in .net technology (2160711)
Collections in .net technology (2160711)Collections in .net technology (2160711)
Collections in .net technology (2160711)
 
Data Structure and its Fundamentals
Data Structure and its FundamentalsData Structure and its Fundamentals
Data Structure and its Fundamentals
 
Analysis of algorithms
Analysis of algorithmsAnalysis of algorithms
Analysis of algorithms
 
Lesson 6 recursion
Lesson 6  recursionLesson 6  recursion
Lesson 6 recursion
 
Lecture11 standard template-library
Lecture11 standard template-libraryLecture11 standard template-library
Lecture11 standard template-library
 
Stack and queue
Stack and queueStack and queue
Stack and queue
 
On Applying Or-Parallelism and Tabling to Logic Programs
On Applying Or-Parallelism and Tabling to Logic ProgramsOn Applying Or-Parallelism and Tabling to Logic Programs
On Applying Or-Parallelism and Tabling to Logic Programs
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Recursion Pattern Analysis and Feedback
Recursion Pattern Analysis and FeedbackRecursion Pattern Analysis and Feedback
Recursion Pattern Analysis and Feedback
 
C++ STL 概觀
C++ STL 概觀C++ STL 概觀
C++ STL 概觀
 
STL in C++
STL in C++STL in C++
STL in C++
 
XQuery Triggers in Native XML Database Sedna
XQuery Triggers in Native XML Database SednaXQuery Triggers in Native XML Database Sedna
XQuery Triggers in Native XML Database Sedna
 

Ähnlich wie 2 a stacks

stack_presentaton_HUSNAIN[2].pojklklklptx
stack_presentaton_HUSNAIN[2].pojklklklptxstack_presentaton_HUSNAIN[2].pojklklklptx
stack_presentaton_HUSNAIN[2].pojklklklptxHusnainNaqvi2
 
01-intro_stacks.ppt
01-intro_stacks.ppt01-intro_stacks.ppt
01-intro_stacks.pptsoniya555961
 
Stacks
StacksStacks
StacksAcad
 
Stacks queues-1220971554378778-9
Stacks queues-1220971554378778-9Stacks queues-1220971554378778-9
Stacks queues-1220971554378778-9Getachew Ganfur
 
Stack linked list
Stack linked listStack linked list
Stack linked listbhargav0077
 
01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seo01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seoJinTaek Seo
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queueRajkiran Nadar
 
5 chapter3 list_stackqueuepart2
5 chapter3 list_stackqueuepart25 chapter3 list_stackqueuepart2
5 chapter3 list_stackqueuepart2SSE_AndyLi
 
computer notes - Data Structures - 5
computer notes - Data Structures - 5computer notes - Data Structures - 5
computer notes - Data Structures - 5ecomputernotes
 
Educational slides by venay magen
Educational slides by venay magenEducational slides by venay magen
Educational slides by venay magenvenaymagen19
 
Stacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti AroraStacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti Arorakulachihansraj
 
Stacks & Queues
Stacks & QueuesStacks & Queues
Stacks & Queuestech4us
 

Ähnlich wie 2 a stacks (20)

Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
 
stack_presentaton_HUSNAIN[2].pojklklklptx
stack_presentaton_HUSNAIN[2].pojklklklptxstack_presentaton_HUSNAIN[2].pojklklklptx
stack_presentaton_HUSNAIN[2].pojklklklptx
 
01-intro_stacks.ppt
01-intro_stacks.ppt01-intro_stacks.ppt
01-intro_stacks.ppt
 
stack.ppt
stack.pptstack.ppt
stack.ppt
 
STACK.pptx
STACK.pptxSTACK.pptx
STACK.pptx
 
Lesson 4 stacks and queues
Lesson 4  stacks and queuesLesson 4  stacks and queues
Lesson 4 stacks and queues
 
Stack in Sata Structure
Stack in Sata StructureStack in Sata Structure
Stack in Sata Structure
 
Stacks
StacksStacks
Stacks
 
Stacks queues-1220971554378778-9
Stacks queues-1220971554378778-9Stacks queues-1220971554378778-9
Stacks queues-1220971554378778-9
 
Rana Junaid Rasheed
Rana Junaid RasheedRana Junaid Rasheed
Rana Junaid Rasheed
 
Stack linked list
Stack linked listStack linked list
Stack linked list
 
01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seo01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seo
 
02 Stack
02 Stack02 Stack
02 Stack
 
notes.pdf
notes.pdfnotes.pdf
notes.pdf
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queue
 
5 chapter3 list_stackqueuepart2
5 chapter3 list_stackqueuepart25 chapter3 list_stackqueuepart2
5 chapter3 list_stackqueuepart2
 
computer notes - Data Structures - 5
computer notes - Data Structures - 5computer notes - Data Structures - 5
computer notes - Data Structures - 5
 
Educational slides by venay magen
Educational slides by venay magenEducational slides by venay magen
Educational slides by venay magen
 
Stacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti AroraStacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti Arora
 
Stacks & Queues
Stacks & QueuesStacks & Queues
Stacks & Queues
 

Kürzlich hochgeladen

Introduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptxIntroduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptxfirstjob4
 
Week-01-2.ppt BBB human Computer interaction
Week-01-2.ppt BBB human Computer interactionWeek-01-2.ppt BBB human Computer interaction
Week-01-2.ppt BBB human Computer interactionfulawalesam
 
Capstone Project on IBM Data Analytics Program
Capstone Project on IBM Data Analytics ProgramCapstone Project on IBM Data Analytics Program
Capstone Project on IBM Data Analytics ProgramMoniSankarHazra
 
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779Best VIP Call Girls Noida Sector 22 Call Me: 8448380779
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779Delhi Call girls
 
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Carero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxCarero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxolyaivanovalion
 
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptxBPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptxMohammedJunaid861692
 
CebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxCebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxolyaivanovalion
 
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% SecureCall me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% SecurePooja Nehwal
 
Vip Model Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...
Vip Model  Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...Vip Model  Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...
Vip Model Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...shivangimorya083
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfMarinCaroMartnezBerg
 
Determinants of health, dimensions of health, positive health and spectrum of...
Determinants of health, dimensions of health, positive health and spectrum of...Determinants of health, dimensions of health, positive health and spectrum of...
Determinants of health, dimensions of health, positive health and spectrum of...shambhavirathore45
 
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...amitlee9823
 
100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptxAnupama Kate
 
VidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptxVidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptxolyaivanovalion
 
Edukaciniai dropshipping via API with DroFx
Edukaciniai dropshipping via API with DroFxEdukaciniai dropshipping via API with DroFx
Edukaciniai dropshipping via API with DroFxolyaivanovalion
 
April 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's AnalysisApril 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's Analysismanisha194592
 

Kürzlich hochgeladen (20)

Introduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptxIntroduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptx
 
Week-01-2.ppt BBB human Computer interaction
Week-01-2.ppt BBB human Computer interactionWeek-01-2.ppt BBB human Computer interaction
Week-01-2.ppt BBB human Computer interaction
 
Capstone Project on IBM Data Analytics Program
Capstone Project on IBM Data Analytics ProgramCapstone Project on IBM Data Analytics Program
Capstone Project on IBM Data Analytics Program
 
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779Best VIP Call Girls Noida Sector 22 Call Me: 8448380779
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779
 
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
 
Carero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxCarero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptx
 
꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...
꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...
꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...
 
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptxBPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
 
CebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxCebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptx
 
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% SecureCall me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
 
Vip Model Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...
Vip Model  Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...Vip Model  Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...
Vip Model Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdf
 
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in  KishangarhDelhi 99530 vip 56974 Genuine Escort Service Call Girls in  Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
 
Determinants of health, dimensions of health, positive health and spectrum of...
Determinants of health, dimensions of health, positive health and spectrum of...Determinants of health, dimensions of health, positive health and spectrum of...
Determinants of health, dimensions of health, positive health and spectrum of...
 
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
 
Sampling (random) method and Non random.ppt
Sampling (random) method and Non random.pptSampling (random) method and Non random.ppt
Sampling (random) method and Non random.ppt
 
100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx
 
VidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptxVidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptx
 
Edukaciniai dropshipping via API with DroFx
Edukaciniai dropshipping via API with DroFxEdukaciniai dropshipping via API with DroFx
Edukaciniai dropshipping via API with DroFx
 
April 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's AnalysisApril 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's Analysis
 

2 a stacks

  • 1. Data Structures and Algorithms in Java 1/19 2. Stack and Queue Part 1: Stack
  • 2. Data Structures and Algorithms in Java 2/19 Stack Objectives • Stacks • Array-based stack • Stack implemented by a singly linked list • Stack class in java.util
  • 3. Data Structures and Algorithms in Java 3/19 What is a stack? 3 • A stack is a linear data structure that can be accessed only at one of its ends for storing and retrieving data • A stack is a Last In, First Out (LIFO) data structure • Anything added to the stack goes on the “top” of the stack • Anything removed from the stack is taken from the “top” of the stack • Things are removed in the reverse order from that in which they were inserted
  • 4. Data Structures and Algorithms in Java 4/19 Operations on a stack 4 • The following operations are needed to properly manage a stack: – clear() — Clear the stack – isEmpty() — Check to see if the stack is empty – push(el) — Put the element el on the top of the stack – pop() — Take the topmost element from the stack – top() — Return the topmost element in the stack without removing it Operations on a stack
  • 5. Data Structures and Algorithms in Java 5/19 Stack Exceptions 5 • 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 StackEmptyException.
  • 6. Data Structures and Algorithms in Java 6/19 Applications of Stacks • Stacks are used for: – Any sort of nesting (such as parentheses) – Evaluating arithmetic expressions (and other sorts of expression) – Implementing function or method calls – Keeping track of previous choices (as in backtracking) – Keeping track of choices yet to be made (as in creating a maze) – Undo sequence in a text editor. – Auxiliary data structure for algorithms – Component of other data structures
  • 7. Data Structures and Algorithms in Java 7/19 Stack in computer memory • How does a stack in memory actually work? – Each time a method is called, an activation record (AR) is allocated for it. This record usually contains the following information: • Parameters and local variables used in the called method. • A dynamic link, which is a pointer to the caller's activation record. • Return address to resume control by the caller, the address of the caller’s instruction immediately following the call. • Return value for a method not declared as void. Because the size of the activation record may vary from one call to another, the returned value is placed right above the activation record of the caller. – Each new activation record is placed on the top of the run-time stack – When a method terminates, its activation record is removed from the top of the run-time stack – Thus, the first AR placed onto the stack is the last one removed AR is also called Stack frame
  • 8. Data Structures and Algorithms in Java 8/19 Array-based Stack - 1 • A simple way of implementing the Stack ADT (abstract data type) uses an array • We add elements from left to right • A variable top keeps track of the index of the top element S 0 1 2 top … Array-based stack
  • 9. Data Structures and Algorithms in Java 9/19 • The array storing the stack elements may become full • A push operation will then throw a FullStackException – Limitation of the array-based implementation – Not intrinsic to the Stack ADT S 0 1 2 top … Array-based Stack - 2 Array-based stack may become full
  • 10. Data Structures and Algorithms in Java 10/19 Array implementation of a stack 10 class ArrayStack {protected Object [] a; int top, max; public ArrayStack() { this(50); } public ArrayStack(int max1) { max = max1; a = new Object[max]; top = -1; } protected boolean grow() { int max1 = max + max/2; Object [] a1 = new Object[max1]; if(a1 == null) return(false); for(int i =0; i<=top; i++) a1[i] = a[i]; a = a1; return(true); } public boolean isEmpty() { return(top==-1);} public boolean isEmpty() { return(top==-1);} public boolean isFull() { return(top==max-1);} public void clear() { top=-1;} public void push(Object x) { if(isFull() && !grow()) return; a[++top] = x; } Object top() throws EmptyStackException { if(isEmpty()) throw new EmptyStackException(); return(a[top]); } public Object pop() throws EmptyStackException { if(isEmpty()) throw new EmptyStackException(); Object x = a[top]; top--; return(x); }
  • 11. Data Structures and Algorithms in Java 11/19 Linked implementation of a stack 11 class Node { public Object info; public Node next; public Node(Object x, Node p) { info=x; next=p; } public Node(Object x) { this(x,null); } }; class LinkedStack { protected Node head; public LinkedStack() { head = null; } public boolean isEmpty() { return(head==null);} public void push(Object x) { head = new Node(x,head); } Object top() throws EmptyStackException { if(isEmpty()) throw new EmptyStackException(); return(head.info); } public Object pop() throws EmptyStackException { if(isEmpty()) throw new EmptyStackException(); Object x = head.info; head=head.next; return(x); }
  • 12. Data Structures and Algorithms in Java 12/19 Implementing a stack using ArrayList & LinkedList classes in Java 12 import java.util.*; class MyStack {ArrayList h; MyStack() {h = new ArrayList();} boolean isEmpty() {return(h.isEmpty());} void push(Object x) {h.add(x); } Object pop() {if(isEmpty()) return(null); return(h.remove(h.size()-1)); } } import java.util.*; class MyStack {LinkedList h; MyStack() {h = new LinkedList();} boolean isEmpty() {return(h.isEmpty());} void push(Object x) {h.add(x); } Object pop() {if(isEmpty()) return(null); return(h.removeLast()); } }
  • 13. Data Structures and Algorithms in Java 13/19 Convert decimal integer number to binary number using a stack 13 public class Main {public static void decToBin(int k) {MyStack s = new MyStack(); System.out.print(k + " in binary system is: "); while(k>0) {s.push(new Integer(k%2)); k = k/2; } while(!s.isEmpty()) System.out.print(s.pop()); System.out.println(); } public static void main(String [] args) {decToBin(11); System.out.println(); } }
  • 14. Data Structures and Algorithms in Java 14/19 Validate expression using stack - 1 14 We consider arithmetic expressions that may contain various pairs of grouping symbols, such as • Parentheses: “(” and “)” • Braces: “{” and “}” • Brackets: “[” and “]” Each opening symbol must match its corresponding closing symbol. For example, a left bracket, “[,” must match a corresponding right bracket, “],” as in the following expression [(5+x)−(y+z)]. The following examples further illustrate this concept: • Correct: ( )(( )){([( )])} • Correct: ((( )(( )){([( )])})) • Incorrect: )(( )){([( )])} • Incorrect: ({[ ])} • Incorrect: ( We leave the precise definition of a matching group of symbols to Exercise R-6.6.
  • 15. Data Structures and Algorithms in Java 15/19 Validate expression using stack - 2 15 An Algorithm for Matching Delimiters: An important task when processing arithmetic expressions is to make sure their delimiting symbols match up correctly. We can use a stack to perform this task with a single left-to-right scan of the original string. Each time we encounter an opening symbol, we push that symbol onto the stack, and each time we encounter a closing symbol, we pop a symbol from the stack (assuming it is not empty) and check that these two symbols form a valid pair. If we reach the end of the expression and the stack is empty, then the original expression was properly matched. Otherwise, there must be an opening delimiter on the stack without a matching symbol. If the length of the original expression is n, the algorithm will make at most n calls to push and n calls to pop.
  • 16. Data Structures and Algorithms in Java 16/19 Matching Parentheses and HTML Tags 16 Another application of matching delimiters is in the validation of markup languages such as HTML or XML. HTML is the standard format for hyperlinked documents on the Internet and XML is an extensible markup language used for a variety of structured data sets. In an HTML document, portions of text are delimited by HTML tags. A simple opening HTML tag has the form “<name>” and the corresponding closing tag has the form “</name>”. For example, the <body> tag has the matching </body> tag at the close of that document. Ideally, an HTML document should have matching tags, although most browsers tolerate a certain number of mismatching tags. We can use stack to check whether an HTML document is valid or not.
  • 17. Data Structures and Algorithms in Java 17/19 Stack class in Java A Stack class implemented in the java.util package is an extension of class Vector to which one constructor and five methods are added. Stack class in Java
  • 18. Data Structures and Algorithms in Java 18/19 Summary 18 • A stack is a linear data structure that can be accessed at only one of its ends for storing and retrieving data. • A stack is called an LIFO structure: last in/first out.
  • 19. Data Structures and Algorithms in Java 19/19 Reading at home Text book: Data Structures and Algorithms in Java. • 6 Stacks, Queues, and Deques 225 • 6.1 Stacks - 226