SlideShare a Scribd company logo
1 of 8
Download to read offline
Implement the ADT stack by using an array stack to contain its entries. Expand the array
dynamically, as necessary. Maintain the stack’s bottom entry in stack[stack.length – 1].
Your Stack class must implement StackInterface (provided). You may use ArrayStack.java
(provided) as the starting point for your implementation.
You must implement a comprehensive set of unit tests using the main() method (and private
utility methods) in ArrayStack.java.
ArrayStack.java
public class ArrayStack implements StackInterface
{
private T[] stack; // Array of stack entries
private int topIndex; // Index of top entry
private boolean initialized = false;
private static final int DEFAULT_CAPACITY = 50;
private static final int MAX_CAPACITY = 10000;
public ArrayStack()
{
this(DEFAULT_CAPACITY);
} // end default constructor
public ArrayStack(int initialCapacity)
{
checkCapacity(initialCapacity);
// The cast is safe because the new array contains null entries
@SuppressWarnings("unchecked")
T[] tempStack = (T[])new Object[initialCapacity];
stack = tempStack;
topIndex = -1;
initialized = true;
} // end constructor
// < Implementations of the stack operations go here. >
// < Implementations of the private methods go here; checkCapacity and
// checkInitialization are analogous to those in Chapter 2. >
// . . .
} // end ArrayStack
StackInterface.java
public interface StackInterface
{
/** Adds a new entry to the top of this stack.
@param newEntry An object to be added to the stack. */
public void push(T newEntry);
/** Removes and returns this stack's top entry.
@return The object at the top of the stack.
@throws EmptyStackException if the stack is empty before the operation. */
public T pop();
/** Retrieves this stack's top entry.
@return The object at the top of the stack.
@throws EmptyStackException if the stack is empty. */
public T peek();
/** Detects whether this stack is empty.
@return True if the stack is empty. */
public boolean isEmpty();
/** Removes all entries from this stack. */
public void clear();
} // end StackInterface
Solution
StackTester.java
public class StackTester
{
public static void main(String[] args)
{
ArrayStack aS = new ArrayStack();
aS.push(3);
aS.push(5);
aS.push(10);
aS.push(11);
System.out.println(""+ aS.peek() + ", " + aS.pop() + ", " + aS.peek2());
aS.remove(1);
}
}
ArrayStack.java
import java.util.Arrays;
public class ArrayStack implements StackInterface
{
private T[] stack;
private int topIndex;
private boolean initialized = false;
private static final int DEFAULT_CAPACITY = 50;
private static final int MAX_CAPACITY = 10000;
public ArrayStack()
{
this(DEFAULT_CAPACITY);
}
public ArrayStack(int initialCapacity)
{
checkCapacity(initialCapacity);
@SuppressWarnings("unchecked")
T[] tempStack = (T[])new Object[initialCapacity];
stack = tempStack;
topIndex = -1;
initialized = true;
}
public boolean isEmpty()
{
return topIndex < 0;
}
private void ensureCapacity()
{
if(topIndex == stack.length - 1)
{
int newLength = 2*stack.length;
checkCapacity(newLength);
stack = Arrays.copyOf(stack, newLength);
}
}
private void ensureCapacity(int n)
{
// add n slots to the array
if(topIndex == stack.length - 1){
int newLength = 2*stack.length + n;
checkCapacity(newLength);
stack = Arrays.copyOf(stack, newLength);
}
}
private boolean checkCapacity(int capacity)
{
boolean bool = true;
if(capacity > MAX_CAPACITY)
bool = false;
return bool;
}
private boolean checkInitialized()
{
return initialized;
}
public void push(T newEntry)
{
checkInitialized();
ensureCapacity();
stack[topIndex+1] = newEntry;
topIndex++;
}
public T pop()
{
checkInitialized();
if(!isEmpty())
{
T top = stack[topIndex];
stack[topIndex]= null;
topIndex --;
return top;
} else
{
throw new ArrayIndexOutOfBoundsException("Stack is empty");
}
}
public T peek()
{
checkInitialized();
if(isEmpty())
{
throw new ArrayIndexOutOfBoundsException("Stack is empty");
} else
return stack[topIndex];
}
public void clear()
{
stack = (T[]) new Object[DEFAULT_CAPACITY];
topIndex = -1;
}
public T peek2()
{
checkInitialized();
if(isEmpty())
{
throw new ArrayIndexOutOfBoundsException("Stack is empty");
} else
return stack[topIndex-1];
}
public String toString()
{
String s = "";
for(int i = 0; i < stack.length; i++)
{
s += stack[i] + ",";
}
return s;
}
public void remove(int n)
{
checkInitialized();
if(n <= topIndex)
{
for(int i = n; i < (topIndex - 1); i++)
{
stack[i] = stack[i+1];
}
}
}
public void pushAll(T[] a)
{
checkInitialized();
checkCapacity(topIndex + a.length);
ensureCapacity(a.length);
for(int i = 0; i < a.length; i ++)
{
stack[topIndex + 1] = a[i];
topIndex ++;
}
}
}
StackInterface.java
public interface StackInterface
{
/** Adds a new entry to the top of this stack. */
public void push(T newEntry);
/** Removes and returns this stack's top entry.*/
public T pop();
/** Retrieves this stack's top entry. */
public T peek();
/** Detects whether this stack is empty. */
public boolean isEmpty();
/** Removes all entries from this stack. */
public void clear();
public T peek2(); // Returns the element below the top element, or throw an exception if there
are less than two elements
public String toString(); // Returns a string that shows all of the elements on the stack. You can
choose the format.
public void remove(int n); // removes the top n entries from the stack. Stops as soon as the
stack is empty.
public void pushAll(T[] a); // pushes each element in the array , beginning with index 0.
}

More Related Content

Similar to Implement the ADT stack by using an array stack to contain its entri.pdf

package algs13;import stdlib.;import java.util.Iterator;im.docx
package algs13;import  stdlib.;import java.util.Iterator;im.docxpackage algs13;import  stdlib.;import java.util.Iterator;im.docx
package algs13;import stdlib.;import java.util.Iterator;im.docxgerardkortney
 
So I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdfSo I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdfaksahnan
 
(674335607) cs2309 java-lab-manual
(674335607) cs2309 java-lab-manual(674335607) cs2309 java-lab-manual
(674335607) cs2309 java-lab-manualChandrapriya Jayabal
 
Java Generics
Java GenericsJava Generics
Java Genericsjeslie
 
Stacks and queue
Stacks and queueStacks and queue
Stacks and queueAmit Vats
 
Please add-modify the following to the original code using C# 1- Delet.docx
Please add-modify the following to the original code using C# 1- Delet.docxPlease add-modify the following to the original code using C# 1- Delet.docx
Please add-modify the following to the original code using C# 1- Delet.docxStewartt0kJohnstonh
 
Educational slides by venay magen
Educational slides by venay magenEducational slides by venay magen
Educational slides by venay magenvenaymagen19
 
Data Structure.pptx
Data Structure.pptxData Structure.pptx
Data Structure.pptxSajalFayyaz
 
ReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfravikapoorindia
 
C program for array implementation of stack#include stdio.h.pdf
 C program for array implementation of stack#include stdio.h.pdf C program for array implementation of stack#include stdio.h.pdf
C program for array implementation of stack#include stdio.h.pdfmohammadirfan136964
 
package singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfpackage singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfamazing2001
 
Were writing code for a project that dynamically allocates an arra.pdf
Were writing code for a project that dynamically allocates an arra.pdfWere writing code for a project that dynamically allocates an arra.pdf
Were writing code for a project that dynamically allocates an arra.pdffsenterprises
 
I have a stack in Java populated with integers. Im trying to compa.pdf
I have a stack in Java populated with integers. Im trying to compa.pdfI have a stack in Java populated with integers. Im trying to compa.pdf
I have a stack in Java populated with integers. Im trying to compa.pdfJUSTSTYLISH3B2MOHALI
 
JAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.pdfJAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.pdffantasiatheoutofthef
 

Similar to Implement the ADT stack by using an array stack to contain its entri.pdf (19)

package algs13;import stdlib.;import java.util.Iterator;im.docx
package algs13;import  stdlib.;import java.util.Iterator;im.docxpackage algs13;import  stdlib.;import java.util.Iterator;im.docx
package algs13;import stdlib.;import java.util.Iterator;im.docx
 
So I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdfSo I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdf
 
(674335607) cs2309 java-lab-manual
(674335607) cs2309 java-lab-manual(674335607) cs2309 java-lab-manual
(674335607) cs2309 java-lab-manual
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Stacks and queue
Stacks and queueStacks and queue
Stacks and queue
 
Please add-modify the following to the original code using C# 1- Delet.docx
Please add-modify the following to the original code using C# 1- Delet.docxPlease add-modify the following to the original code using C# 1- Delet.docx
Please add-modify the following to the original code using C# 1- Delet.docx
 
Educational slides by venay magen
Educational slides by venay magenEducational slides by venay magen
Educational slides by venay magen
 
Data Structure.pptx
Data Structure.pptxData Structure.pptx
Data Structure.pptx
 
ReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdf
 
Posfix
PosfixPosfix
Posfix
 
C program for array implementation of stack#include stdio.h.pdf
 C program for array implementation of stack#include stdio.h.pdf C program for array implementation of stack#include stdio.h.pdf
C program for array implementation of stack#include stdio.h.pdf
 
Lec2
Lec2Lec2
Lec2
 
package singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfpackage singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdf
 
Stack and queue
Stack and queueStack and queue
Stack and queue
 
Were writing code for a project that dynamically allocates an arra.pdf
Were writing code for a project that dynamically allocates an arra.pdfWere writing code for a project that dynamically allocates an arra.pdf
Were writing code for a project that dynamically allocates an arra.pdf
 
stack presentation
stack presentationstack presentation
stack presentation
 
I have a stack in Java populated with integers. Im trying to compa.pdf
I have a stack in Java populated with integers. Im trying to compa.pdfI have a stack in Java populated with integers. Im trying to compa.pdf
I have a stack in Java populated with integers. Im trying to compa.pdf
 
JAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.pdfJAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.pdf
 
Collection and framework
Collection and frameworkCollection and framework
Collection and framework
 

More from SIGMATAX1

Consider a binary search tree T with nodes containing the four fields.pdf
Consider a binary search tree T with nodes containing the four fields.pdfConsider a binary search tree T with nodes containing the four fields.pdf
Consider a binary search tree T with nodes containing the four fields.pdfSIGMATAX1
 
Based on the articleWhy It Is Time to Look Beyond Algal Genes in P.pdf
Based on the articleWhy It Is Time to Look Beyond Algal Genes in P.pdfBased on the articleWhy It Is Time to Look Beyond Algal Genes in P.pdf
Based on the articleWhy It Is Time to Look Beyond Algal Genes in P.pdfSIGMATAX1
 
Comparecontrast the following classes of hormones by identifying thr.pdf
Comparecontrast the following classes of hormones by identifying thr.pdfComparecontrast the following classes of hormones by identifying thr.pdf
Comparecontrast the following classes of hormones by identifying thr.pdfSIGMATAX1
 
Why does the incidence of acute disease decrease with ageSoluti.pdf
Why does the incidence of acute disease decrease with ageSoluti.pdfWhy does the incidence of acute disease decrease with ageSoluti.pdf
Why does the incidence of acute disease decrease with ageSoluti.pdfSIGMATAX1
 
White eye color in Drosophila was discovered to be sex linked by Tho.pdf
White eye color in Drosophila was discovered to be sex linked by Tho.pdfWhite eye color in Drosophila was discovered to be sex linked by Tho.pdf
White eye color in Drosophila was discovered to be sex linked by Tho.pdfSIGMATAX1
 
Which of the following protons would you NOT expect to find embedded .pdf
Which of the following protons would you NOT expect to find embedded .pdfWhich of the following protons would you NOT expect to find embedded .pdf
Which of the following protons would you NOT expect to find embedded .pdfSIGMATAX1
 
Which of these characteristics distinguishes angiosperms from other .pdf
Which of these characteristics distinguishes angiosperms from other .pdfWhich of these characteristics distinguishes angiosperms from other .pdf
Which of these characteristics distinguishes angiosperms from other .pdfSIGMATAX1
 
Which of the following is MOST responsible for maintaining the doubl.pdf
Which of the following is MOST responsible for maintaining the doubl.pdfWhich of the following is MOST responsible for maintaining the doubl.pdf
Which of the following is MOST responsible for maintaining the doubl.pdfSIGMATAX1
 
What are the role of environmental factors on transpiration and h.pdf
What are the role of environmental factors on transpiration and h.pdfWhat are the role of environmental factors on transpiration and h.pdf
What are the role of environmental factors on transpiration and h.pdfSIGMATAX1
 
What will be quantization step size in numbers and in voltage for th.pdf
What will be quantization step size in numbers and in voltage for th.pdfWhat will be quantization step size in numbers and in voltage for th.pdf
What will be quantization step size in numbers and in voltage for th.pdfSIGMATAX1
 
What is the need for a shadow page table (One or two brief sentences.pdf
What is the need for a shadow page table (One or two brief sentences.pdfWhat is the need for a shadow page table (One or two brief sentences.pdf
What is the need for a shadow page table (One or two brief sentences.pdfSIGMATAX1
 
What step of protein synthesis is shown in the figure elongation st.pdf
What step of protein synthesis is shown in the figure  elongation st.pdfWhat step of protein synthesis is shown in the figure  elongation st.pdf
What step of protein synthesis is shown in the figure elongation st.pdfSIGMATAX1
 
Water is forced through a contraction causing low pressure. The wat.pdf
Water is forced through a contraction causing low pressure. The wat.pdfWater is forced through a contraction causing low pressure. The wat.pdf
Water is forced through a contraction causing low pressure. The wat.pdfSIGMATAX1
 
Using a PIC 18 Write a time overflow interrupt routine that detects .pdf
Using a PIC 18 Write a time overflow interrupt routine that detects .pdfUsing a PIC 18 Write a time overflow interrupt routine that detects .pdf
Using a PIC 18 Write a time overflow interrupt routine that detects .pdfSIGMATAX1
 
The three types of mixtures are and The weak bond forming a bridge .pdf
The three types of mixtures are  and  The weak bond forming a bridge .pdfThe three types of mixtures are  and  The weak bond forming a bridge .pdf
The three types of mixtures are and The weak bond forming a bridge .pdfSIGMATAX1
 
Some commercial airplanes recirculate approximately 50 of the cabin .pdf
Some commercial airplanes recirculate approximately 50 of the cabin .pdfSome commercial airplanes recirculate approximately 50 of the cabin .pdf
Some commercial airplanes recirculate approximately 50 of the cabin .pdfSIGMATAX1
 
Solve for 02 sin 2+sin 5=0. Separate your answers with commas.pdf
Solve for 02 sin 2+sin 5=0. Separate your answers with commas.pdfSolve for 02 sin 2+sin 5=0. Separate your answers with commas.pdf
Solve for 02 sin 2+sin 5=0. Separate your answers with commas.pdfSIGMATAX1
 
Required 1. Briefly describe different computer controls available .pdf
Required 1. Briefly describe different computer controls available .pdfRequired 1. Briefly describe different computer controls available .pdf
Required 1. Briefly describe different computer controls available .pdfSIGMATAX1
 
a. What is Snort [1]b. According to “Snort Users Manual” (downloa.pdf
a. What is Snort [1]b. According to “Snort Users Manual” (downloa.pdfa. What is Snort [1]b. According to “Snort Users Manual” (downloa.pdf
a. What is Snort [1]b. According to “Snort Users Manual” (downloa.pdfSIGMATAX1
 
Proponents of decentralized forms of socialism usually supportA co.pdf
Proponents of decentralized forms of socialism usually supportA co.pdfProponents of decentralized forms of socialism usually supportA co.pdf
Proponents of decentralized forms of socialism usually supportA co.pdfSIGMATAX1
 

More from SIGMATAX1 (20)

Consider a binary search tree T with nodes containing the four fields.pdf
Consider a binary search tree T with nodes containing the four fields.pdfConsider a binary search tree T with nodes containing the four fields.pdf
Consider a binary search tree T with nodes containing the four fields.pdf
 
Based on the articleWhy It Is Time to Look Beyond Algal Genes in P.pdf
Based on the articleWhy It Is Time to Look Beyond Algal Genes in P.pdfBased on the articleWhy It Is Time to Look Beyond Algal Genes in P.pdf
Based on the articleWhy It Is Time to Look Beyond Algal Genes in P.pdf
 
Comparecontrast the following classes of hormones by identifying thr.pdf
Comparecontrast the following classes of hormones by identifying thr.pdfComparecontrast the following classes of hormones by identifying thr.pdf
Comparecontrast the following classes of hormones by identifying thr.pdf
 
Why does the incidence of acute disease decrease with ageSoluti.pdf
Why does the incidence of acute disease decrease with ageSoluti.pdfWhy does the incidence of acute disease decrease with ageSoluti.pdf
Why does the incidence of acute disease decrease with ageSoluti.pdf
 
White eye color in Drosophila was discovered to be sex linked by Tho.pdf
White eye color in Drosophila was discovered to be sex linked by Tho.pdfWhite eye color in Drosophila was discovered to be sex linked by Tho.pdf
White eye color in Drosophila was discovered to be sex linked by Tho.pdf
 
Which of the following protons would you NOT expect to find embedded .pdf
Which of the following protons would you NOT expect to find embedded .pdfWhich of the following protons would you NOT expect to find embedded .pdf
Which of the following protons would you NOT expect to find embedded .pdf
 
Which of these characteristics distinguishes angiosperms from other .pdf
Which of these characteristics distinguishes angiosperms from other .pdfWhich of these characteristics distinguishes angiosperms from other .pdf
Which of these characteristics distinguishes angiosperms from other .pdf
 
Which of the following is MOST responsible for maintaining the doubl.pdf
Which of the following is MOST responsible for maintaining the doubl.pdfWhich of the following is MOST responsible for maintaining the doubl.pdf
Which of the following is MOST responsible for maintaining the doubl.pdf
 
What are the role of environmental factors on transpiration and h.pdf
What are the role of environmental factors on transpiration and h.pdfWhat are the role of environmental factors on transpiration and h.pdf
What are the role of environmental factors on transpiration and h.pdf
 
What will be quantization step size in numbers and in voltage for th.pdf
What will be quantization step size in numbers and in voltage for th.pdfWhat will be quantization step size in numbers and in voltage for th.pdf
What will be quantization step size in numbers and in voltage for th.pdf
 
What is the need for a shadow page table (One or two brief sentences.pdf
What is the need for a shadow page table (One or two brief sentences.pdfWhat is the need for a shadow page table (One or two brief sentences.pdf
What is the need for a shadow page table (One or two brief sentences.pdf
 
What step of protein synthesis is shown in the figure elongation st.pdf
What step of protein synthesis is shown in the figure  elongation st.pdfWhat step of protein synthesis is shown in the figure  elongation st.pdf
What step of protein synthesis is shown in the figure elongation st.pdf
 
Water is forced through a contraction causing low pressure. The wat.pdf
Water is forced through a contraction causing low pressure. The wat.pdfWater is forced through a contraction causing low pressure. The wat.pdf
Water is forced through a contraction causing low pressure. The wat.pdf
 
Using a PIC 18 Write a time overflow interrupt routine that detects .pdf
Using a PIC 18 Write a time overflow interrupt routine that detects .pdfUsing a PIC 18 Write a time overflow interrupt routine that detects .pdf
Using a PIC 18 Write a time overflow interrupt routine that detects .pdf
 
The three types of mixtures are and The weak bond forming a bridge .pdf
The three types of mixtures are  and  The weak bond forming a bridge .pdfThe three types of mixtures are  and  The weak bond forming a bridge .pdf
The three types of mixtures are and The weak bond forming a bridge .pdf
 
Some commercial airplanes recirculate approximately 50 of the cabin .pdf
Some commercial airplanes recirculate approximately 50 of the cabin .pdfSome commercial airplanes recirculate approximately 50 of the cabin .pdf
Some commercial airplanes recirculate approximately 50 of the cabin .pdf
 
Solve for 02 sin 2+sin 5=0. Separate your answers with commas.pdf
Solve for 02 sin 2+sin 5=0. Separate your answers with commas.pdfSolve for 02 sin 2+sin 5=0. Separate your answers with commas.pdf
Solve for 02 sin 2+sin 5=0. Separate your answers with commas.pdf
 
Required 1. Briefly describe different computer controls available .pdf
Required 1. Briefly describe different computer controls available .pdfRequired 1. Briefly describe different computer controls available .pdf
Required 1. Briefly describe different computer controls available .pdf
 
a. What is Snort [1]b. According to “Snort Users Manual” (downloa.pdf
a. What is Snort [1]b. According to “Snort Users Manual” (downloa.pdfa. What is Snort [1]b. According to “Snort Users Manual” (downloa.pdf
a. What is Snort [1]b. According to “Snort Users Manual” (downloa.pdf
 
Proponents of decentralized forms of socialism usually supportA co.pdf
Proponents of decentralized forms of socialism usually supportA co.pdfProponents of decentralized forms of socialism usually supportA co.pdf
Proponents of decentralized forms of socialism usually supportA co.pdf
 

Recently uploaded

Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
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
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 

Recently uploaded (20)

Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
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
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 

Implement the ADT stack by using an array stack to contain its entri.pdf

  • 1. Implement the ADT stack by using an array stack to contain its entries. Expand the array dynamically, as necessary. Maintain the stack’s bottom entry in stack[stack.length – 1]. Your Stack class must implement StackInterface (provided). You may use ArrayStack.java (provided) as the starting point for your implementation. You must implement a comprehensive set of unit tests using the main() method (and private utility methods) in ArrayStack.java. ArrayStack.java public class ArrayStack implements StackInterface { private T[] stack; // Array of stack entries private int topIndex; // Index of top entry private boolean initialized = false; private static final int DEFAULT_CAPACITY = 50; private static final int MAX_CAPACITY = 10000; public ArrayStack() { this(DEFAULT_CAPACITY); } // end default constructor public ArrayStack(int initialCapacity) { checkCapacity(initialCapacity); // The cast is safe because the new array contains null entries @SuppressWarnings("unchecked") T[] tempStack = (T[])new Object[initialCapacity]; stack = tempStack; topIndex = -1; initialized = true; } // end constructor // < Implementations of the stack operations go here. > // < Implementations of the private methods go here; checkCapacity and // checkInitialization are analogous to those in Chapter 2. >
  • 2. // . . . } // end ArrayStack StackInterface.java public interface StackInterface { /** Adds a new entry to the top of this stack. @param newEntry An object to be added to the stack. */ public void push(T newEntry); /** Removes and returns this stack's top entry. @return The object at the top of the stack. @throws EmptyStackException if the stack is empty before the operation. */ public T pop(); /** Retrieves this stack's top entry. @return The object at the top of the stack. @throws EmptyStackException if the stack is empty. */ public T peek(); /** Detects whether this stack is empty. @return True if the stack is empty. */ public boolean isEmpty(); /** Removes all entries from this stack. */ public void clear(); } // end StackInterface Solution StackTester.java public class StackTester { public static void main(String[] args) { ArrayStack aS = new ArrayStack();
  • 3. aS.push(3); aS.push(5); aS.push(10); aS.push(11); System.out.println(""+ aS.peek() + ", " + aS.pop() + ", " + aS.peek2()); aS.remove(1); } } ArrayStack.java import java.util.Arrays; public class ArrayStack implements StackInterface { private T[] stack; private int topIndex; private boolean initialized = false; private static final int DEFAULT_CAPACITY = 50; private static final int MAX_CAPACITY = 10000; public ArrayStack() { this(DEFAULT_CAPACITY); } public ArrayStack(int initialCapacity) { checkCapacity(initialCapacity); @SuppressWarnings("unchecked") T[] tempStack = (T[])new Object[initialCapacity]; stack = tempStack; topIndex = -1; initialized = true;
  • 4. } public boolean isEmpty() { return topIndex < 0; } private void ensureCapacity() { if(topIndex == stack.length - 1) { int newLength = 2*stack.length; checkCapacity(newLength); stack = Arrays.copyOf(stack, newLength); } } private void ensureCapacity(int n) { // add n slots to the array if(topIndex == stack.length - 1){ int newLength = 2*stack.length + n; checkCapacity(newLength); stack = Arrays.copyOf(stack, newLength); } } private boolean checkCapacity(int capacity) { boolean bool = true; if(capacity > MAX_CAPACITY) bool = false; return bool; } private boolean checkInitialized()
  • 5. { return initialized; } public void push(T newEntry) { checkInitialized(); ensureCapacity(); stack[topIndex+1] = newEntry; topIndex++; } public T pop() { checkInitialized(); if(!isEmpty()) { T top = stack[topIndex]; stack[topIndex]= null; topIndex --; return top; } else { throw new ArrayIndexOutOfBoundsException("Stack is empty"); } } public T peek() { checkInitialized(); if(isEmpty()) { throw new ArrayIndexOutOfBoundsException("Stack is empty"); } else
  • 6. return stack[topIndex]; } public void clear() { stack = (T[]) new Object[DEFAULT_CAPACITY]; topIndex = -1; } public T peek2() { checkInitialized(); if(isEmpty()) { throw new ArrayIndexOutOfBoundsException("Stack is empty"); } else return stack[topIndex-1]; } public String toString() { String s = ""; for(int i = 0; i < stack.length; i++) { s += stack[i] + ","; } return s; } public void remove(int n) { checkInitialized(); if(n <= topIndex) { for(int i = n; i < (topIndex - 1); i++)
  • 7. { stack[i] = stack[i+1]; } } } public void pushAll(T[] a) { checkInitialized(); checkCapacity(topIndex + a.length); ensureCapacity(a.length); for(int i = 0; i < a.length; i ++) { stack[topIndex + 1] = a[i]; topIndex ++; } } } StackInterface.java public interface StackInterface { /** Adds a new entry to the top of this stack. */ public void push(T newEntry); /** Removes and returns this stack's top entry.*/ public T pop(); /** Retrieves this stack's top entry. */ public T peek(); /** Detects whether this stack is empty. */ public boolean isEmpty(); /** Removes all entries from this stack. */
  • 8. public void clear(); public T peek2(); // Returns the element below the top element, or throw an exception if there are less than two elements public String toString(); // Returns a string that shows all of the elements on the stack. You can choose the format. public void remove(int n); // removes the top n entries from the stack. Stops as soon as the stack is empty. public void pushAll(T[] a); // pushes each element in the array , beginning with index 0. }