SlideShare uma empresa Scribd logo
1 de 25
Stacks
public interface Stack
{
public boolean empty();
public Object peek();
public void push(Object theObject);
public Object pop();
}
Derive From A Linear List Class
• ArrayLinearList
• Chain
Derive From ArrayLinearList
 stack top is either left end or right end of linear
list
 empty() => isEmpty()
• O(1) time
 peek() => get(0) or get(size() - 1)
• O(1) time
0 1 2 3 4 5 6
a b c d e
Derive From ArrayLinearList
• when top is left end of linear list
 push(theObject) => add(0, theObject)
 O(size) time
 pop() => remove(0)
 O(size) time
0 1 2 3 4 5 6
a b c d e
Derive From ArrayLinearList
 when top is right end of linear list
• push(theObject) => add(size(), theObject)
• O(1) time
• pop() => remove(size()-1)
• O(1) time
 use right end of list as top of stack
0 1 2 3 4 5 6
a b c d e
Derive From Chain
 stack top is either left end or right end of
linear list
 empty() => isEmpty()
• O(1) time
a b c d e
null
firstNode
Derive From Chain
a b c d e
null
firstNode
– when top is left end of linear list
 peek() => get(0)
 O(1) time
 push(theObject) => add(0, theObject)
 O(1) time
 pop() => remove(0)
 O(1) time
Derive From Chain
a b c d e
null
firstNode
– when top is right end of linear list
• peek() => get(size() - 1)
• O(size) time
• push(theObject) => add(size(), theObject)
• O(size) time
• pop() => remove(size()-1)
• O(size) time
– use left end of list as top of stack
Derive From ArrayLinearList
package dataStructures;
import java.util.*; // has stack exception
public class DerivedArrayStack
extends ArrayLinearList
implements Stack
{
// constructors come here
// Stack interface methods come here
}
Constructors
/** create a stack with the given initial
* capacity */
public DerivedArrayStack(int initialCapacity)
{super(initialCapacity);}
/** create a stack with initial capacity 10 */
public DerivedArrayStack()
{this(10);}
empty() And peek()
public boolean empty()
{return isEmpty();}
public Object peek()
{
if (empty())
throw new EmptyStackException();
return get(size() - 1)
}
0 1 2 3 4 5 6
a b c d e
push(theObject) And pop()
public void push(Object theElement)
{add(size(), theElement);}
public Object pop()
{
if (empty())
throw new EmptyStackException();
return remove(size() - 1);
}
0 1 2 3 4 5 6
a b c d e
Evaluation
• Merits of deriving from ArrayLinearList
 Code for derived class is quite simple and easy to
develop.
 Code is expected to require little debugging.
 Code for other stack implementations such as a
linked implementation are easily obtained.
• Just replace extends ArrayLinearList with extends Chain
• For efficiency reasons we must also make changes to use
the left end of the list as the stack top rather than the right
end.
Demerits
• All public methods of ArrayLinearList may be
performed on a stack.
 get(0) … get bottom element
 remove(5)
 add(3, x)
 So we do not have a true stack implementation.
 Must override undesired methods.
public Object get(int theIndex)
{throw new UnsupportedOperationException();}
Change earlier use of get(i) to super.get(i).
Demerits
• Unecessary work is done by the code.
 peek() verifies that the stack is not empty before get
is invoked. The index check done by get is,
therefore, not needed.
 add(size(), theElement) does an index check and a
for loop that is not entered. Neither is needed.
 pop() verifies that the stack is not empty before
remove is invoked. remove does an index check and
a for loop that is not entered. Neither is needed.
 So the derived code runs slower than necessary.
Evaluation
• Code developed from scratch will run faster but
will take more time (cost) to develop.
• Tradeoff between software development cost
and performance.
• Tradeoff between time to market and
performance.
• Could develop easy code first and later refine it
to improve performance.
A Faster pop()
if (empty())
throw new EmptyStackException();
return remove(size() - 1);
vs.
try {return remove(size() - 1);}
catch(IndexOutOfBoundsException e)
{throw new EmptyStackException();}
Code From Scratch
• Use a 1D array stack whose data type is Object.
 same as using array element in ArrayLinearList
• Use an int variable top.
 Stack elements are in stack[0:top].
 Top element is in stack[top].
 Bottom element is in stack[0].
 Stack is empty iff top = -1.
 Number of elements in stack is top+1.
Code From Scratch
package dataStructures;
import java.util.EmptyStackException;
import utilities.*; // ChangeArrayLength
public class ArrayStack implements Stack
{
// data members
int top; // current top of stack
Object [] stack; // element array
// constructors come here
// Stack interface methods come here
}
Constructors
public ArrayStack(int initialCapacity)
{
if (initialCapacity < 1)
throw new IllegalArgumentException
("initialCapacity must be >= 1");
stack = new Object [initialCapacity];
top = -1;
}
public ArrayStack()
{this(10);}
push(…)
public void push(Object theElement)
{
// increase array size if necessary
if (top == stack.length - 1)
stack = ChangeArrayLength.changeLength1D
(stack, 2 * stack.length);
// put theElement at the top of the stack
stack[++top] = theElement;
}
0 1 2 3 4
a b c d e
top
pop()
public Object pop()
{
if (empty())
throw new EmptyStackException();
Object topElement = stack[top];
stack[top--] = null; // enable garbage collection
return topElement;
}
0 1 2 3 4
a b c d e
top
Linked Stack From Scratch
• See text.
java.util.Stack
• Derives from java.util.Vector.
• java.util.Vector is an array implementation
of a linear list.
Performance
500,000 pop, push, and peek operations
initial capacity
Class 10 500,000
ArrayStack 0.44s 0.22s
DerivedArrayStack 0.60s 0.38s
DerivedArrayStackWithCatch 0.55s 0.33s
java.util.Stack 1.15s -
DerivedLinkedStack 3.20s 3.20s
LinkedStack 2.96s 2.96s

Mais conteúdo relacionado

Mais procurados

Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaEdureka!
 
Spark schema for free with David Szakallas
Spark schema for free with David SzakallasSpark schema for free with David Szakallas
Spark schema for free with David SzakallasDatabricks
 
An Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
An Introduction to Higher Order Functions in Spark SQL with Herman van HovellAn Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
An Introduction to Higher Order Functions in Spark SQL with Herman van HovellDatabricks
 
Spark Schema For Free with David Szakallas
 Spark Schema For Free with David Szakallas Spark Schema For Free with David Szakallas
Spark Schema For Free with David SzakallasDatabricks
 
Introduction to Apache Flink
Introduction to Apache FlinkIntroduction to Apache Flink
Introduction to Apache Flinkmxmxm
 
Chapter 6: stack data structure
Chapter 6:  stack data structureChapter 6:  stack data structure
Chapter 6: stack data structureMahmoud Alfarra
 
openCypher Technology Compatibility Kit (TCK)
openCypher Technology Compatibility Kit (TCK)openCypher Technology Compatibility Kit (TCK)
openCypher Technology Compatibility Kit (TCK)openCypher
 
The Ring programming language version 1.5.4 book - Part 10 of 185
The Ring programming language version 1.5.4 book - Part 10 of 185The Ring programming language version 1.5.4 book - Part 10 of 185
The Ring programming language version 1.5.4 book - Part 10 of 185Mahmoud Samir Fayed
 
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn TớiTech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn TớiNexus FrontierTech
 
The Ring programming language version 1.5.3 book - Part 10 of 184
The Ring programming language version 1.5.3 book - Part 10 of 184The Ring programming language version 1.5.3 book - Part 10 of 184
The Ring programming language version 1.5.3 book - Part 10 of 184Mahmoud Samir Fayed
 
Reactive Extensions (Rx)
Reactive Extensions (Rx)Reactive Extensions (Rx)
Reactive Extensions (Rx)Mark Allan
 
Jug Marche: Meeting June 2014. Java 8 hands on
Jug Marche: Meeting June 2014. Java 8 hands onJug Marche: Meeting June 2014. Java 8 hands on
Jug Marche: Meeting June 2014. Java 8 hands onOnofrio Panzarino
 
Scala Collections : Java 8 on Steroids
Scala Collections : Java 8 on SteroidsScala Collections : Java 8 on Steroids
Scala Collections : Java 8 on SteroidsFrançois Garillot
 
Ruslan Shevchenko - Property based testing
Ruslan Shevchenko - Property based testingRuslan Shevchenko - Property based testing
Ruslan Shevchenko - Property based testingIevgenii Katsan
 
Functional linear data structures in f#
Functional linear data structures in f#Functional linear data structures in f#
Functional linear data structures in f#Jack Fox
 

Mais procurados (20)

Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | Edureka
 
Spark schema for free with David Szakallas
Spark schema for free with David SzakallasSpark schema for free with David Szakallas
Spark schema for free with David Szakallas
 
02 stackqueue
02 stackqueue02 stackqueue
02 stackqueue
 
An Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
An Introduction to Higher Order Functions in Spark SQL with Herman van HovellAn Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
An Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
 
Spark Schema For Free with David Szakallas
 Spark Schema For Free with David Szakallas Spark Schema For Free with David Szakallas
Spark Schema For Free with David Szakallas
 
Introduction to Apache Flink
Introduction to Apache FlinkIntroduction to Apache Flink
Introduction to Apache Flink
 
Chapter 6: stack data structure
Chapter 6:  stack data structureChapter 6:  stack data structure
Chapter 6: stack data structure
 
openCypher Technology Compatibility Kit (TCK)
openCypher Technology Compatibility Kit (TCK)openCypher Technology Compatibility Kit (TCK)
openCypher Technology Compatibility Kit (TCK)
 
Chapter 4 stack
Chapter 4 stackChapter 4 stack
Chapter 4 stack
 
The Ring programming language version 1.5.4 book - Part 10 of 185
The Ring programming language version 1.5.4 book - Part 10 of 185The Ring programming language version 1.5.4 book - Part 10 of 185
The Ring programming language version 1.5.4 book - Part 10 of 185
 
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn TớiTech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
 
Collections
CollectionsCollections
Collections
 
Command Liner with Scala
Command Liner with ScalaCommand Liner with Scala
Command Liner with Scala
 
The Ring programming language version 1.5.3 book - Part 10 of 184
The Ring programming language version 1.5.3 book - Part 10 of 184The Ring programming language version 1.5.3 book - Part 10 of 184
The Ring programming language version 1.5.3 book - Part 10 of 184
 
Reactive Extensions (Rx)
Reactive Extensions (Rx)Reactive Extensions (Rx)
Reactive Extensions (Rx)
 
Jug Marche: Meeting June 2014. Java 8 hands on
Jug Marche: Meeting June 2014. Java 8 hands onJug Marche: Meeting June 2014. Java 8 hands on
Jug Marche: Meeting June 2014. Java 8 hands on
 
Scala Collections : Java 8 on Steroids
Scala Collections : Java 8 on SteroidsScala Collections : Java 8 on Steroids
Scala Collections : Java 8 on Steroids
 
Ruslan Shevchenko - Property based testing
Ruslan Shevchenko - Property based testingRuslan Shevchenko - Property based testing
Ruslan Shevchenko - Property based testing
 
Functional linear data structures in f#
Functional linear data structures in f#Functional linear data structures in f#
Functional linear data structures in f#
 
Collections
CollectionsCollections
Collections
 

Semelhante a Educational slides by venay magen

Stack and its applications
Stack and its applicationsStack and its applications
Stack and its applicationsAhsan Mansiv
 
(674335607) cs2309 java-lab-manual
(674335607) cs2309 java-lab-manual(674335607) cs2309 java-lab-manual
(674335607) cs2309 java-lab-manualChandrapriya Jayabal
 
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority QueueWhat is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority QueueBalwant Gorad
 
Stack Implementation
Stack ImplementationStack Implementation
Stack ImplementationZidny Nafan
 
My lecture stack_queue_operation
My lecture stack_queue_operationMy lecture stack_queue_operation
My lecture stack_queue_operationSenthil Kumar
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIjagriti srivastava
 
Please review my code (java)Someone helped me with it but i cannot.pdf
Please review my code (java)Someone helped me with it but i cannot.pdfPlease review my code (java)Someone helped me with it but i cannot.pdf
Please review my code (java)Someone helped me with it but i cannot.pdffathimafancyjeweller
 
Stack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxStack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxchandankumar364348
 
Ch03_stacks_and_queues.ppt
Ch03_stacks_and_queues.pptCh03_stacks_and_queues.ppt
Ch03_stacks_and_queues.pptOliverKane3
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queueRajkiran Nadar
 
13 Stacks and Queues.pptx
13 Stacks and Queues.pptx13 Stacks and Queues.pptx
13 Stacks and Queues.pptxssuserb7c8b8
 

Semelhante a Educational slides by venay magen (20)

Stack and its applications
Stack and its applicationsStack and its applications
Stack and its applications
 
stack presentation
stack presentationstack presentation
stack presentation
 
U3.stack queue
U3.stack queueU3.stack queue
U3.stack queue
 
LectureNotes-06-DSA
LectureNotes-06-DSALectureNotes-06-DSA
LectureNotes-06-DSA
 
9 python data structure-2
9 python data structure-29 python data structure-2
9 python data structure-2
 
STACK1.pptx
STACK1.pptxSTACK1.pptx
STACK1.pptx
 
(674335607) cs2309 java-lab-manual
(674335607) cs2309 java-lab-manual(674335607) cs2309 java-lab-manual
(674335607) cs2309 java-lab-manual
 
2 a stacks
2 a stacks2 a stacks
2 a stacks
 
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority QueueWhat is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
 
notes.pdf
notes.pdfnotes.pdf
notes.pdf
 
Stack Implementation
Stack ImplementationStack Implementation
Stack Implementation
 
My lecture stack_queue_operation
My lecture stack_queue_operationMy lecture stack_queue_operation
My lecture stack_queue_operation
 
Stacks
StacksStacks
Stacks
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time API
 
Please review my code (java)Someone helped me with it but i cannot.pdf
Please review my code (java)Someone helped me with it but i cannot.pdfPlease review my code (java)Someone helped me with it but i cannot.pdf
Please review my code (java)Someone helped me with it but i cannot.pdf
 
Java Stack (Pilha)
Java Stack (Pilha)Java Stack (Pilha)
Java Stack (Pilha)
 
Stack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxStack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptx
 
Ch03_stacks_and_queues.ppt
Ch03_stacks_and_queues.pptCh03_stacks_and_queues.ppt
Ch03_stacks_and_queues.ppt
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queue
 
13 Stacks and Queues.pptx
13 Stacks and Queues.pptx13 Stacks and Queues.pptx
13 Stacks and Queues.pptx
 

Último

Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdfssuserdda66b
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 

Último (20)

Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 

Educational slides by venay magen

  • 1. Stacks public interface Stack { public boolean empty(); public Object peek(); public void push(Object theObject); public Object pop(); }
  • 2. Derive From A Linear List Class • ArrayLinearList • Chain
  • 3. Derive From ArrayLinearList  stack top is either left end or right end of linear list  empty() => isEmpty() • O(1) time  peek() => get(0) or get(size() - 1) • O(1) time 0 1 2 3 4 5 6 a b c d e
  • 4. Derive From ArrayLinearList • when top is left end of linear list  push(theObject) => add(0, theObject)  O(size) time  pop() => remove(0)  O(size) time 0 1 2 3 4 5 6 a b c d e
  • 5. Derive From ArrayLinearList  when top is right end of linear list • push(theObject) => add(size(), theObject) • O(1) time • pop() => remove(size()-1) • O(1) time  use right end of list as top of stack 0 1 2 3 4 5 6 a b c d e
  • 6. Derive From Chain  stack top is either left end or right end of linear list  empty() => isEmpty() • O(1) time a b c d e null firstNode
  • 7. Derive From Chain a b c d e null firstNode – when top is left end of linear list  peek() => get(0)  O(1) time  push(theObject) => add(0, theObject)  O(1) time  pop() => remove(0)  O(1) time
  • 8. Derive From Chain a b c d e null firstNode – when top is right end of linear list • peek() => get(size() - 1) • O(size) time • push(theObject) => add(size(), theObject) • O(size) time • pop() => remove(size()-1) • O(size) time – use left end of list as top of stack
  • 9. Derive From ArrayLinearList package dataStructures; import java.util.*; // has stack exception public class DerivedArrayStack extends ArrayLinearList implements Stack { // constructors come here // Stack interface methods come here }
  • 10. Constructors /** create a stack with the given initial * capacity */ public DerivedArrayStack(int initialCapacity) {super(initialCapacity);} /** create a stack with initial capacity 10 */ public DerivedArrayStack() {this(10);}
  • 11. empty() And peek() public boolean empty() {return isEmpty();} public Object peek() { if (empty()) throw new EmptyStackException(); return get(size() - 1) } 0 1 2 3 4 5 6 a b c d e
  • 12. push(theObject) And pop() public void push(Object theElement) {add(size(), theElement);} public Object pop() { if (empty()) throw new EmptyStackException(); return remove(size() - 1); } 0 1 2 3 4 5 6 a b c d e
  • 13. Evaluation • Merits of deriving from ArrayLinearList  Code for derived class is quite simple and easy to develop.  Code is expected to require little debugging.  Code for other stack implementations such as a linked implementation are easily obtained. • Just replace extends ArrayLinearList with extends Chain • For efficiency reasons we must also make changes to use the left end of the list as the stack top rather than the right end.
  • 14. Demerits • All public methods of ArrayLinearList may be performed on a stack.  get(0) … get bottom element  remove(5)  add(3, x)  So we do not have a true stack implementation.  Must override undesired methods. public Object get(int theIndex) {throw new UnsupportedOperationException();} Change earlier use of get(i) to super.get(i).
  • 15. Demerits • Unecessary work is done by the code.  peek() verifies that the stack is not empty before get is invoked. The index check done by get is, therefore, not needed.  add(size(), theElement) does an index check and a for loop that is not entered. Neither is needed.  pop() verifies that the stack is not empty before remove is invoked. remove does an index check and a for loop that is not entered. Neither is needed.  So the derived code runs slower than necessary.
  • 16. Evaluation • Code developed from scratch will run faster but will take more time (cost) to develop. • Tradeoff between software development cost and performance. • Tradeoff between time to market and performance. • Could develop easy code first and later refine it to improve performance.
  • 17. A Faster pop() if (empty()) throw new EmptyStackException(); return remove(size() - 1); vs. try {return remove(size() - 1);} catch(IndexOutOfBoundsException e) {throw new EmptyStackException();}
  • 18. Code From Scratch • Use a 1D array stack whose data type is Object.  same as using array element in ArrayLinearList • Use an int variable top.  Stack elements are in stack[0:top].  Top element is in stack[top].  Bottom element is in stack[0].  Stack is empty iff top = -1.  Number of elements in stack is top+1.
  • 19. Code From Scratch package dataStructures; import java.util.EmptyStackException; import utilities.*; // ChangeArrayLength public class ArrayStack implements Stack { // data members int top; // current top of stack Object [] stack; // element array // constructors come here // Stack interface methods come here }
  • 20. Constructors public ArrayStack(int initialCapacity) { if (initialCapacity < 1) throw new IllegalArgumentException ("initialCapacity must be >= 1"); stack = new Object [initialCapacity]; top = -1; } public ArrayStack() {this(10);}
  • 21. push(…) public void push(Object theElement) { // increase array size if necessary if (top == stack.length - 1) stack = ChangeArrayLength.changeLength1D (stack, 2 * stack.length); // put theElement at the top of the stack stack[++top] = theElement; } 0 1 2 3 4 a b c d e top
  • 22. pop() public Object pop() { if (empty()) throw new EmptyStackException(); Object topElement = stack[top]; stack[top--] = null; // enable garbage collection return topElement; } 0 1 2 3 4 a b c d e top
  • 23. Linked Stack From Scratch • See text.
  • 24. java.util.Stack • Derives from java.util.Vector. • java.util.Vector is an array implementation of a linear list.
  • 25. Performance 500,000 pop, push, and peek operations initial capacity Class 10 500,000 ArrayStack 0.44s 0.22s DerivedArrayStack 0.60s 0.38s DerivedArrayStackWithCatch 0.55s 0.33s java.util.Stack 1.15s - DerivedLinkedStack 3.20s 3.20s LinkedStack 2.96s 2.96s

Notas do Editor

  1. The decision whether to use the left or right end of the linear list as the stack top is made on the basis of efficiency of resulting stack methods. The complexity of empty() and peek() are independent of the choice.
  2. The complexity of empty() is independent of which end of the chain is used as the top of the stack. The complexity of the remaining methods depends on which end is the stack top.