Question

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 and count the nodes.

//----------------------------------------------------------------
// ArrayStack.java by Dale/Joyce/Weems Chapter 3
//
// Implements BoundedStackInterface using an array to hold the
// stack elements.
//
// Two constructors are provided: one that creates an array of a
// default size and one that allows the calling program to
// specify the size.
//----------------------------------------------------------------

package ch03.stacks;

public class ArrayStack<T> implements BoundedStackInterface<T>
{
protected final int DEFCAP = 100; // default capacity
protected T[] stack; // holds stack elements
protected int topIndex = -1; // index of top element in stack

public ArrayStack()
{
stack = (T[]) new Object[DEFCAP];
}

public ArrayStack(int maxSize)
{
stack = (T[]) new Object[maxSize];
}

public void push(T element)
// Throws StackOverflowException if this stack is full,
// otherwise places element at the top of this stack.
{
if (!isFull())
{
topIndex++;
stack[topIndex] = element;
}
else
throw new StackOverflowException("Push attempted on a full stack.");
}

public void pop()
// Throws StackUnderflowException if this stack is empty,
// otherwise removes top element from this stack.
{
if (!isEmpty())
{
stack[topIndex] = null;
topIndex--;
}
else
throw new StackUnderflowException("Pop attempted on an empty stack.");
}

public T top()
// Throws StackUnderflowException if this stack is empty,
// otherwise returns top element from this stack.
{   
T topOfStack = null;
if (!isEmpty())
topOfStack = stack[topIndex];
else
throw new StackUnderflowException("Top attempted on an empty stack.");
return topOfStack;
}

public boolean isEmpty()
// Returns true if this stack is empty, otherwise returns false.
{
if (topIndex == -1)
return true;
else
return false;
}

public boolean isFull()
// Returns true if this stack is full, otherwise returns false.
{
if (topIndex == (stack.length - 1))
return true;
else
return false;
}
}

//----------------------------------------------------------------------
// LinkedStack.java by Dale/Joyce/Weems Chapter 3
//
// Implements UnboundedStackInterface using a linked list
// to hold the stack elements.
//-----------------------------------------------------------------------

package ch03.stacks;

import support.LLNode;

public class LinkedStack implements UnboundedStackInterface
{
protected LLNode top; // reference to the top of this stack
public LinkedStack()

{
top = null;
}

public void push(T element)

// Places element at the top of this stack.
{
LLNode newNode = new LLNode(element);
newNode.setLink(top);
top = newNode;
}   

public void pop()

// Throws StackUnderflowException if this stack is empty,
// otherwise removes top element from this stack.
{
if (!isEmpty())
{
top = top.getLink();
}
else
throw new StackUnderflowException("Pop attempted on an empty stack.");
}

public T top()

// Throws StackUnderflowException if this stack is empty,
// otherwise returns top element from this stack.
{   
if (!isEmpty())
return top.getInfo();
else
throw new StackUnderflowException("Top attempted on an empty stack.");
}

public boolean isEmpty()
// Returns true if this stack is empty, otherwise returns false.
{
if (top == null)
return true;
else
return false;
}
@Override
//ToDo #42
public String toString ()
{   
   return "Need to Implement in LinkedStack class";
}
//ToDo #46a "walk"
public int sizeIs()
{
   return -100;
}
}

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

#ArrayStack

public int sizels()

{

return topIndex; // topIndex represents the top of the array stack which is equal to number of elements in it

}

#LinkedStack

public int sizels()

{

for(i=1;top.getLink();i++)

top=top.getLink();

return i;

}

Add a comment
Know the answer?
Add Answer to:
Suppose we decide to add a new operation to our Stack ADT called sizeIs, which returns...
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
  • Dynamic Implementation of Stack - The purpose is to use our dynamic implementation of stack. The...

    Dynamic Implementation of Stack - The purpose is to use our dynamic implementation of stack. The application will be to add large numbers. Review adding large numbers Remember that we can use stacks to safely add integer values that overflow the int data type g. in Java, the maximum possible int value Integer.MAX_VALUE is: 2147483647 so any int addition larger than this will overflow and fail Using stacks to add large numbers safely Will actually represent the large integers to...

  • I have a java project that I need help trying to finish. I have most of it completed but the issue I am running into is adding numbers with different lengths. Project requirements: . Use a Stack ADT w...

    I have a java project that I need help trying to finish. I have most of it completed but the issue I am running into is adding numbers with different lengths. Project requirements: . Use a Stack ADT with the implementation of your choice (Array or Link), it should not make a difference 2.Read two “integer” numbers from the user. Hint: You don’t need to use an int type when you read, it may be easier to parse the input...

  • 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...

  • 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...

  • Complete the implementation of the LinkedStack class presented in Chapter 13. Specifically, complete the implementations of...

    Complete the implementation of the LinkedStack class presented in Chapter 13. Specifically, complete the implementations of the peek, isEmpty, size, and toString methods. See Base_A06Q1.java for a starting place and a description of these methods. Here is the base given: /** * Write a description of the program here. * * @author Lewis et al., (your name) * @version (program version) */ import java.util.Iterator; public class Base_A06Q1 { /** * Program entry point for stack testing. * @param args Argument...

  • 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...

  • Recursively sorting an unbounded stack (java) in ascending order? (This assignment is only limited to stacks...

    Recursively sorting an unbounded stack (java) in ascending order? (This assignment is only limited to stacks only, No other data structures are allowed) My professor gave us a hint on how to implement this, however she wants the comparable interface to be used. im not sure on how to do this. Hint: May want to use a public method that accepts the original stack and then creates the two additional stacks needed. This method then calls a private method that...

  • 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...

  • In addition to the base files, three additional files are attached: EmptyCollectionException.java, LinearNode.java, and StackADT.java. These...

    In addition to the base files, three additional files are attached: EmptyCollectionException.java, LinearNode.java, and StackADT.java. These files will need to be added to your Java project. They provide data structure functionality that you will build over. It is suggested that you test if these files have been properly added to your project by confirming that Base_A05Q1.java compiles correctly. Complete the implementation of the ArrayStack class. Specifically, complete the implementations of the isEmpty, size, and toString methods. See Base_A05Q1.java for a...

  • 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...

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