Question

Java - data structures Suppose that in the array-based stack, the array doubles in size after...

Java - data structures

Suppose that in the array-based stack, the array doubles in size after multiple push operations. But later on, fewer than half of the array’s locations might actually be used by the stack due to pop operations.

Revise the implementation so that its array also can shrink in size as objects are removed from the stack. Accomplishing this task will require two new private methods, as follows:

The first new method checks whether we should reduce the size of the array:

private boolean isTooBig()

This method returns true if the number of entries in the stack is less than half the size of the array and the size of the array is greater than 20.

The second new method creates a new array that is three quarters the size of the current array and then copies the objects in the bag to the new array:

private void reduceArray()

Implement each of these two methods, and then use them in the definition of pop()

Arraystack2:

import java.util.Arrays;
public class ArrayStack2<T> implements StackInterface<T>
{
private T[] stack; // array of stack entries
private int topIndex; // index of top entry
private static final int DEFAULT_INITIAL_CAPACITY = 50;
  
public ArrayStack2()
{
this(DEFAULT_INITIAL_CAPACITY);
} // end default constructor
  
public ArrayStack2(int initialCapacity)
{
// the cast is safe because the new array contains null entries
@SuppressWarnings("unchecked")
T[] tempStack = (T[])new Object[initialCapacity];
stack = tempStack;
topIndex = -1;
} // end constructor
  
public void push(T newEntry)   
{
ensureCapacity();
topIndex++;
stack[topIndex] = newEntry;   
} // end push   

private void ensureCapacity()   
{ if (topIndex == stack.length - 1) // if array is full, double size of array
   stack = Arrays.copyOf(stack, 2 * stack.length);   
} // end ensureCapacity

public T peek()   
{
T top = null;   
if (!isEmpty())   
   top = stack[topIndex];   
return top;   
} // end peek

public T pop()
{
T top = null;

if (!isEmpty()) {
   top = stack[topIndex];
   stack[topIndex] = null;
   topIndex--;
} // end if

return top;
} // end pop

public boolean isEmpty()
{   
return topIndex < 0;
} // end isEmpty

public void clear()
{
for(int i = 0; i <= topIndex; ++i)
   stack[i] = null;
topIndex = -1;
}

} // end ArrayStack

Stackinterface


public interface StackInterface<T>
{
/** 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 either the object at the top of the stack or, if the
stack is empty before the operation, null */
public T pop();
  
/** Retrieves this stack's top entry.
@return either the object at the top of the stack or null 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

linkedStack:

public class LinkedStack<T> implements StackInterface<T>
{
private Node topNode; // references the first node in the chain
  
public LinkedStack()
{
topNode = null;
} // end default constructor
  
public void push(T newEntry)
{   
Node newNode = new Node(newEntry, topNode); topNode = newNode;
} // end push

public T peek()
{   
T top = null;   
if (topNode != null)
   top = topNode.getData();   
return top;
} // end peek

public T pop()
{
T top = peek();   
if (topNode != null)
   topNode = topNode.getNextNode();   
return top;
} // end pop

public boolean isEmpty() {
return topNode == null;
}
public void clear() {
topNode = null;
}

private class Node
{
private T data; // entry in stack
private Node next; // link to next node

private Node(T dataPortion)
{
this(dataPortion, null);
} // end constructor
  
private Node(T dataPortion, Node nextNode)
{
data = dataPortion;
next = nextNode;
} // end constructor
  
private T getData()
{
return data;
} // end getData
  
private void setData(T newData)
{
data = newData;
} // end setData
  
private Node getNextNode()
{
return next;
} // end getNextNode
  
private void setNextNode(Node nextNode)
{
next = nextNode;
} // end setNextNode
} // end Node
} // end LinkedStack

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Problem 3 and 4 :

Note these methods are not tested . You can test and let me know if there is anything. I will be able to fix it if there is any gap.

private boolean isTooBig() {

       if (topIndex + 1 < stack.length / 2 && stack.length > 20)

           return true;

       else

           return false;

   }

Problem 4:

   private void reduceArray() {

       int newcapacity = 3 * stack.length / 4;

       stack = Arrays.copyOf(stack, newcapacity);

   }


This can be used in follwing way in Pop

See This is how it is used in POP

public T pop()

{

T top = null;

if(isTooBig())

   reduceArray();

if (!isEmpty()) {

   top = stack[topIndex];

   stack[topIndex] = null;

   topIndex--;

} // end if

return top;

} // end pop

Thanks, let me know if there is any issues/concern. I will be happily solving those.

Add a comment
Know the answer?
Add Answer to:
Java - data structures Suppose that in the array-based stack, the array doubles in size after...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Currently, I'm getting this as my output: "Exception in thread "main" java.lang.NullPointerException    at InfixExpression.execute(InfixExpression.java:98)   ...

    Currently, I'm getting this as my output: "Exception in thread "main" java.lang.NullPointerException    at InfixExpression.execute(InfixExpression.java:98)    at InfixExpression.Evaluate(InfixExpression.java:65)    at InfixExpression.setWholeExpr(InfixExpression.java:24)    at InfixExpression.<init>(InfixExpression.java:17)    at Main.testHW1(Main.java:17)    at Main.main(Main.java:6)" I need to get this as my output: "Testing InfixExpression: When passing null, the String and double = Infix String: , result: 0.0 When passing a valid String, the String and double = Infix String: ( 234.5 * ( 5.6 + 7.0 ) ) / 100.2, result: 29.488023952095805 ..." I...

  • Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an ...

    Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an array. Implement all methods in ArrayStack class using resizable array strategy, i.e. usedoubleArray() Must throw StackException during exception events in methods:    peek(), pop(), ArrayStack(int initialCapacity) Do not change or add data fields Do not add new methods */ import java.util.Arrays; public class Arraystack«Т> implements Stack!nterface«T> private TI stack;// Array of stack entries private int topIndex; /7 Index of top entry private static...

  • QUESTION: ADT stack: resizable array-based implementation    for Ch4 programming problem 4 "maintain the stacks's top...

    QUESTION: ADT stack: resizable array-based implementation    for Ch4 programming problem 4 "maintain the stacks's top entry at the end of the array" at array index N-1 where the array is currently allocated to hold up to N entries. MAKE SURE YOU IMPLEMENT the functions:  bool isEmpty() const; bool push(const ItemType& newEntry); bool pop(); in ArrayStackP4.cpp //FILE StackInterface.h #ifndef STACK_INTERFACE_ #define STACK_INTERFACE_ template<class ItemType> class StackInterface { public:    /** Sees whether this stack is empty.    @return True if the...

  • I have added a little Code but I need help with the rest. /** A class...

    I have added a little Code but I need help with the rest. /** A class of stacks whose entries are stored in a chain of nodes. Implement all methods in MyStack class Main Reference : text book or class notes Do not change or add data fields */ package PJ2; public class MyStack<T> implements StackInterface<T> {    // Data fields    private Node<T> topNode; // references the first node in the chain    private int numberOfEntries;       public...

  • JAVA Lab Create a class called ArrayBasedStack. Declare the following variables: • data: references an array...

    JAVA Lab Create a class called ArrayBasedStack. Declare the following variables: • data: references an array storing elements in the list • topOfStack: an int value representing the location of the stack top in the array • INITIAL_CAPACITY: the default capacity of the stack public class ArrayBasedStack <E> { private E[] data; private int topOfStack; private static final int INITIAL_CAPACITY = 5; } Add a constructor that will initialize the stack with a user-defined initial capacity. The top of the...

  • Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored...

    Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an array. Implement all methods in ArrayStack class using resizable array strategy, i.e. usedoubleArray() Must throw StackException during exception events in methods:    peek(), pop(), ArrayStack(int initialCapacity) Do not change or add data fields Do not add new methods */ import java.util.Arrays; public class Arraystack«Т> implements Stack!nterface«T> private TI stack;// Array of stack entries private int topIndex; /7 Index of top entry private...

  • Suppose we decide to add a new operation to our Stack ADT called sizeIs, which returns...

    Suppose we decide to add a new operation to our Stack ADT called sizeIs, which returns a value of primitive type int equal to the number of items on the stack. The method signature for sizeIS is public int sizeIs() a.) Write the code for sizeIs for the ArrayStack class b.) Write the code for sizeIs for the LinkedStack class (do not add any instance variables to the class; each time sizeIs is called you must "walk" through the stack...

  • There is a data structure called a drop-out stack that behaves like a stack in every...

    There is a data structure called a drop-out stack that behaves like a stack in every respect except that if the stack size is n, then when the n+1element is pushed, the bottom element is lost. Implement a drop-out stack using links, by modifying the LinkedStack code. (size, n, is provided by the constructor. Request: Please create a separate driver class, in a different file, that tests on different types of entries and show result of the tests done on...

  • I need to implement a stack array but the top of the stack has to be...

    I need to implement a stack array but the top of the stack has to be Initialize as the index of the last location in the array.    //Array implementation of stacks.    import java.util.Arrays;       public class ArrayStack implements Stack {        //Declare a class constant called DEFAULT_STACK_SIZE with the value 10.           private static final int DEFAULT_STACK_SIZE = 10;           /* Declare two instance variables:            1. An integer called...

  • Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,In...

    Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,Integer. Im not sure how to fix this. public class Evaluator { public static void evaluatePost(String postFix)    {        LinkedStack stack2 = new LinkedStack();        int val1;        int val2;        int result;        for(int i = 0; i < postFix.length(); i++)        {            char m = postFix.charAt(i);            if(Character.isDigit(m))            {                stack2.push(m);            }            else            {               ...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT