SlideShare a Scribd company logo
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

More Related Content

What's hot

Searching Algorithms
Searching AlgorithmsSearching Algorithms
Searching Algorithms
Afaq Mansoor Khan
 
Data structure
Data structureData structure
Data structure
Muhammad Farhan
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
GauravPatil318
 
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 algorithms
Hoang Nguyen
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Moniruzzaman _
 
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 Fundamentals
Hitesh Mohapatra
 
Analysis of algorithms
Analysis of algorithmsAnalysis of algorithms
Analysis of algorithms
iqbalphy1
 
Lesson 6 recursion
Lesson 6  recursionLesson 6  recursion
Lesson 6 recursion
MLG College of Learning, Inc
 
Lecture11 standard template-library
Lecture11 standard template-libraryLecture11 standard template-library
Lecture11 standard template-libraryHariz Mustafa
 
Stack and queue
Stack and queueStack and queue
Stack and queue
CHANDAN KUMAR
 
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
Lino Possamai
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
Julie Iskander
 
Recursion Pattern Analysis and Feedback
Recursion Pattern Analysis and FeedbackRecursion Pattern Analysis and Feedback
Recursion Pattern Analysis and Feedback
Sander Mak (@Sander_Mak)
 
C++ STL 概觀
C++ STL 概觀C++ STL 概觀
C++ STL 概觀
PingLun Liao
 
STL in C++
STL in C++STL in C++
STL in C++
Surya Prakash Sahu
 
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
 

What's hot (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
 

Similar to 2 a stacks

Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
Apurbo Datta
 
stack_presentaton_HUSNAIN[2].pojklklklptx
stack_presentaton_HUSNAIN[2].pojklklklptxstack_presentaton_HUSNAIN[2].pojklklklptx
stack_presentaton_HUSNAIN[2].pojklklklptx
HusnainNaqvi2
 
01-intro_stacks.ppt
01-intro_stacks.ppt01-intro_stacks.ppt
01-intro_stacks.ppt
soniya555961
 
stack.ppt
stack.pptstack.ppt
stack.ppt
ssuserec1395
 
STACK.pptx
STACK.pptxSTACK.pptx
STACK.pptx
Dr.Shweta
 
Lesson 4 stacks and queues
Lesson 4  stacks and queuesLesson 4  stacks and queues
Lesson 4 stacks and queues
MLG College of Learning, Inc
 
Stack in Sata Structure
Stack in Sata StructureStack in Sata Structure
Stack in Sata Structure
Muhazzab Chouhadry
 
Stacks
StacksStacks
Stacks
Acad
 
Rana Junaid Rasheed
Rana Junaid RasheedRana Junaid Rasheed
Rana Junaid Rasheed
Rana junaid Rasheed
 
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_seo
JinTaek Seo
 
02 Stack
02 Stack02 Stack
notes.pdf
notes.pdfnotes.pdf
notes.pdf
ssuserd14cca
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queue
Rajkiran Nadar
 
5 chapter3 list_stackqueuepart2
5 chapter3 list_stackqueuepart25 chapter3 list_stackqueuepart2
5 chapter3 list_stackqueuepart2
SSE_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 magen
venaymagen19
 
Stacks & Queues
Stacks & QueuesStacks & Queues
Stacks & Queuestech4us
 
Stacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti AroraStacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti Arora
kulachihansraj
 

Similar to 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
 
Rana Junaid Rasheed
Rana Junaid RasheedRana Junaid Rasheed
Rana Junaid Rasheed
 
Stacks queues-1220971554378778-9
Stacks queues-1220971554378778-9Stacks queues-1220971554378778-9
Stacks queues-1220971554378778-9
 
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
Stacks & QueuesStacks & Queues
Stacks & Queues
 
Stacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti AroraStacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti Arora
 

Recently uploaded

standardisation of garbhpala offhgfffghh
standardisation of garbhpala offhgfffghhstandardisation of garbhpala offhgfffghh
standardisation of garbhpala offhgfffghh
ArpitMalhotra16
 
Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...
Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...
Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...
Subhajit Sahu
 
一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理
一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理
一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理
ahzuo
 
Ch03-Managing the Object-Oriented Information Systems Project a.pdf
Ch03-Managing the Object-Oriented Information Systems Project a.pdfCh03-Managing the Object-Oriented Information Systems Project a.pdf
Ch03-Managing the Object-Oriented Information Systems Project a.pdf
haila53
 
一比一原版(NYU毕业证)纽约大学毕业证成绩单
一比一原版(NYU毕业证)纽约大学毕业证成绩单一比一原版(NYU毕业证)纽约大学毕业证成绩单
一比一原版(NYU毕业证)纽约大学毕业证成绩单
ewymefz
 
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
nscud
 
一比一原版(UniSA毕业证书)南澳大学毕业证如何办理
一比一原版(UniSA毕业证书)南澳大学毕业证如何办理一比一原版(UniSA毕业证书)南澳大学毕业证如何办理
一比一原版(UniSA毕业证书)南澳大学毕业证如何办理
slg6lamcq
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单
ewymefz
 
一比一原版(BU毕业证)波士顿大学毕业证成绩单
一比一原版(BU毕业证)波士顿大学毕业证成绩单一比一原版(BU毕业证)波士顿大学毕业证成绩单
一比一原版(BU毕业证)波士顿大学毕业证成绩单
ewymefz
 
Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...
Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...
Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...
John Andrews
 
Criminal IP - Threat Hunting Webinar.pdf
Criminal IP - Threat Hunting Webinar.pdfCriminal IP - Threat Hunting Webinar.pdf
Criminal IP - Threat Hunting Webinar.pdf
Criminal IP
 
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
yhkoc
 
Q1’2024 Update: MYCI’s Leap Year Rebound
Q1’2024 Update: MYCI’s Leap Year ReboundQ1’2024 Update: MYCI’s Leap Year Rebound
Q1’2024 Update: MYCI’s Leap Year Rebound
Oppotus
 
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
nscud
 
Best best suvichar in gujarati english meaning of this sentence as Silk road ...
Best best suvichar in gujarati english meaning of this sentence as Silk road ...Best best suvichar in gujarati english meaning of this sentence as Silk road ...
Best best suvichar in gujarati english meaning of this sentence as Silk road ...
AbhimanyuSinha9
 
一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理
一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理
一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理
slg6lamcq
 
一比一原版(UVic毕业证)维多利亚大学毕业证成绩单
一比一原版(UVic毕业证)维多利亚大学毕业证成绩单一比一原版(UVic毕业证)维多利亚大学毕业证成绩单
一比一原版(UVic毕业证)维多利亚大学毕业证成绩单
ukgaet
 
一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理
一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理
一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理
oz8q3jxlp
 
Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...
Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...
Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...
Subhajit Sahu
 
一比一原版(UofS毕业证书)萨省大学毕业证如何办理
一比一原版(UofS毕业证书)萨省大学毕业证如何办理一比一原版(UofS毕业证书)萨省大学毕业证如何办理
一比一原版(UofS毕业证书)萨省大学毕业证如何办理
v3tuleee
 

Recently uploaded (20)

standardisation of garbhpala offhgfffghh
standardisation of garbhpala offhgfffghhstandardisation of garbhpala offhgfffghh
standardisation of garbhpala offhgfffghh
 
Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...
Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...
Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...
 
一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理
一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理
一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理
 
Ch03-Managing the Object-Oriented Information Systems Project a.pdf
Ch03-Managing the Object-Oriented Information Systems Project a.pdfCh03-Managing the Object-Oriented Information Systems Project a.pdf
Ch03-Managing the Object-Oriented Information Systems Project a.pdf
 
一比一原版(NYU毕业证)纽约大学毕业证成绩单
一比一原版(NYU毕业证)纽约大学毕业证成绩单一比一原版(NYU毕业证)纽约大学毕业证成绩单
一比一原版(NYU毕业证)纽约大学毕业证成绩单
 
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
 
一比一原版(UniSA毕业证书)南澳大学毕业证如何办理
一比一原版(UniSA毕业证书)南澳大学毕业证如何办理一比一原版(UniSA毕业证书)南澳大学毕业证如何办理
一比一原版(UniSA毕业证书)南澳大学毕业证如何办理
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单
 
一比一原版(BU毕业证)波士顿大学毕业证成绩单
一比一原版(BU毕业证)波士顿大学毕业证成绩单一比一原版(BU毕业证)波士顿大学毕业证成绩单
一比一原版(BU毕业证)波士顿大学毕业证成绩单
 
Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...
Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...
Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...
 
Criminal IP - Threat Hunting Webinar.pdf
Criminal IP - Threat Hunting Webinar.pdfCriminal IP - Threat Hunting Webinar.pdf
Criminal IP - Threat Hunting Webinar.pdf
 
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
 
Q1’2024 Update: MYCI’s Leap Year Rebound
Q1’2024 Update: MYCI’s Leap Year ReboundQ1’2024 Update: MYCI’s Leap Year Rebound
Q1’2024 Update: MYCI’s Leap Year Rebound
 
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
 
Best best suvichar in gujarati english meaning of this sentence as Silk road ...
Best best suvichar in gujarati english meaning of this sentence as Silk road ...Best best suvichar in gujarati english meaning of this sentence as Silk road ...
Best best suvichar in gujarati english meaning of this sentence as Silk road ...
 
一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理
一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理
一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理
 
一比一原版(UVic毕业证)维多利亚大学毕业证成绩单
一比一原版(UVic毕业证)维多利亚大学毕业证成绩单一比一原版(UVic毕业证)维多利亚大学毕业证成绩单
一比一原版(UVic毕业证)维多利亚大学毕业证成绩单
 
一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理
一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理
一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理
 
Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...
Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...
Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...
 
一比一原版(UofS毕业证书)萨省大学毕业证如何办理
一比一原版(UofS毕业证书)萨省大学毕业证如何办理一比一原版(UofS毕业证书)萨省大学毕业证如何办理
一比一原版(UofS毕业证书)萨省大学毕业证如何办理
 

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