Question

public class NumStack implements Comparable{ private Integer[] data; private int index; public NumStack(int cap){ data=new Integer[cap];...

public class NumStack implements Comparable{
private Integer[] data;
private int index;
public NumStack(int cap){
data=new Integer[cap];
index =-1;
}
public boolean isEmpty(){
return index == -1;
}
public boolean isFull(){
return index==data.length -1;
}
public NumStack pop(){
if(!isEmpty()) data[index--]=null;
return this;
}
public int size(){
return index+1;
}
public Integer top(){
if(isEmpty()) return null;
return data[index];
}
public NumStack push(int num){
if(index < data.length-1)
data[++index]=num;
return this;
}
public int compareTo(NumStack s){}
}

public int compareTo(NumStack s) compares two stack from the bottom of each stack, for example, s1[2,0, 9] and s2[9,0,9], calling s1.compareTo(s2) should return -1,
s1 s2
top 9 9 3rd: 9==9 we get 0
0 0 2nd: 0==0 we get 0
bottom 2 9 1st: 2<9 we get -1
------------------------------------------
add all and return: -1
If the two stacks have different sizes, then we consider the ith item is greater than the "none-existing item" in the smaller stack. For example, s1[8,0, -9] and s2[1], calling s1.compareTo(s2) should return 3,
s1 s2
top -9 3rd: no item in s1 ->1
0 2nd: no item in s2 ->1
bottom 8 1 1st: 8>1 ->1
-----------------------------------------
add all and return: 3

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

Here is the completed code for this problem. Also included a Test class to test compareTo method, ignore if you don’t need it. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

// NumStack.java

public class NumStack implements Comparable<NumStack> {

      private Integer[] data;

      private int index;

      public NumStack(int cap) {

            data = new Integer[cap];

            index = -1;

      }

      public boolean isEmpty() {

            return index == -1;

      }

      public boolean isFull() {

            return index == data.length - 1;

      }

      public NumStack pop() {

            if (!isEmpty())

                  data[index--] = null;

            return this;

      }

      public int size() {

            return index + 1;

      }

      public Integer top() {

            if (isEmpty())

                  return null;

            return data[index];

      }

      public NumStack push(int num) {

            if (index < data.length - 1)

                  data[++index] = num;

            return this;

      }

      public int compareTo(NumStack s) {

            int n = 0;

            // finding the last index of bigger stack and assigning to n

            if (this.size() >= s.size()) {

                  n = this.size() - 1;

            } else {

                  n = s.size() - 1;

            }

            // initializing a variable to store sum of all comparison results

            int returnValue = 0;

            // looping as long as n is not negative

            while (n >= 0) {

                  // declaring two variables

                  int num1, num2;

                  // checking if n is a valid index on this stack

                  if (n >= this.size()) {

                       // not a valid index, assigning MIN_VALUE to num1 so that any

                       // number will possibly be greater than this 'non existant'

                       // number

                       num1 = Integer.MIN_VALUE;

                  } else {

                       // n is a valid index, fetching current value to num1

                       num1 = this.data[n];

                  }

                  // checking if n is a valid index on s stack

                  if (n >= s.size()) {

                       // not a valid index, assigning MIN_VALUE to num2 so that any

                       // number will possibly be greater than this 'non existant'

                       // number

                       num2 = Integer.MIN_VALUE;

                  } else {

                       // n is a valid index, fetching current value to num2

                       num2 = s.data[n];

                  }

                  // now actually comparing these two numbers

                  if (num1 < num2) {

                       // num1 comes before num2

                       returnValue += -1;

                  } else if (num1 > num2) {

                       // num2 comes before num1

                       returnValue += 1;

                  } // else we add 0, so it is not required

                  n--; // moving to previous index

            }

            return returnValue;

      }

}

// Test.java (ignore it if you don’t need it)

public class Test {

      public static void main(String[] args) {

            // creating two stacks

            NumStack stack1 = new NumStack(10);

            NumStack stack2 = new NumStack(10);

            // adding 2,0,9 to stack1

            stack1.push(2);

            stack1.push(0);

            stack1.push(9);

            // adding 9,0,9 to stack2

            stack2.push(9);

            stack2.push(0);

            stack2.push(9);

            // comparing stack1 and stack2, should display -1

            System.out.println(stack1.compareTo(stack2));

            // re initializing stacks

            stack1 = new NumStack(10);

            // pushing 8,0,9

            stack1.push(8);

            stack1.push(0);

            stack1.push(-9);

            stack2 = new NumStack(10);

            // pushing only 1

            stack2.push(1);

            // comparing stack[8,0,9] to stack[1] should display 3

            System.out.println(stack1.compareTo(stack2));

      }

}

/*OUTPUT*/

-1

3

Add a comment
Know the answer?
Add Answer to:
public class NumStack implements Comparable{ private Integer[] data; private int index; public NumStack(int cap){ data=new Integer[cap];...
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
  • how do I change my code to generic form *********************************************************************** public class UnboundedStackQueue { //question#3 }...

    how do I change my code to generic form *********************************************************************** public class UnboundedStackQueue { //question#3 } class Stack { Node head; int size; Stack() //default constructor { this.head=null; this.size=0; } //Input = data //Output = void (just adds value to list) // method pushes elements on stack // time: O(1) // space: O(1) public void push(int data) { Node node=new Node(data); node.next=head; head=node; size++; } //Input = none //Output = top of stack // method pops value from top of...

  • how would I complete this code without calling any built-in java collection framework classes like ArrayList,...

    how would I complete this code without calling any built-in java collection framework classes like ArrayList, LinkedList, etc? import java.util.Iterator; class CallStack<T> implements Iterable<T> { // You'll want some instance variables here public CallStack() { //setup what you need } public void push(T item) { //push an item onto the stack //you may assume the item is not null //O(1) } public T pop() { //pop an item off the stack //if there are no items on the stack, return...

  • public class PQueue<E extends Comparable<E>> { private E[] elements; private int size; private int head; private...

    public class PQueue<E extends Comparable<E>> { private E[] elements; private int size; private int head; private int tail; Private int count;   } public void enqueue(E item) { if(isFull()){ return; } count++; elements[tail] = item; tail = (tail + 1) % size; } public E dequeue() { if(isEmpty()) return null; int ct = count-1; E cur = elements[head]; int index = 0; for(i=1;ct-->0;i++) { if(cur.compareTo(elements[head+i)%size])<0) cur = elements[(head+i)%size]; index = i; } } return remove((head+index%size); public E remove(int index) { E...

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

  • public class Item implements Comparable { private String name; private double price; /** * Constructor for...

    public class Item implements Comparable { private String name; private double price; /** * Constructor for objects of class Item * @param theName name of item * @param thePrice price of item */ public Item(String theName, double thePrice) { name = theName; price = thePrice; }    /** * gets the name * @return name name of item */ public String getName() { return name; }    /** * gets price of item * @return price price of item */...

  • Adapt your Rational class : public class Rational { private int num; private int denom; public...

    Adapt your Rational class : public class Rational { private int num; private int denom; public Rational() { num = 0; denom = 1; } public Rational(int num, int denom) { this.num = num; this.denom = denom; } int getNum() { return num; } int getDenom() { return denom; } public Rational add(Rational rhs) { return new Rational(num * rhs.denom + rhs.num * denom, denom * rhs.denom); } public Rational subtract(Rational rhs) { return new Rational(num * rhs.denom - rhs.num...

  • JAVA Implement a MyQueue class which implements a queue using two stacks. private int maxCapacity...

    JAVA Implement a MyQueue class which implements a queue using two stacks. private int maxCapacity = 4; private Stack stack1; private Stack stack2; Note: You can use library Stack but you are not allowed to use library Queue and any of its methods Your Queue should not accept null or empty String or space as an input You need to implement the following methods using two stacks (stack1 & stack2) and also you can add more methods as well: public...

  • In Java. What would the methods of this class look like? StackADT.java public interface StackADT<T> {...

    In Java. What would the methods of this class look like? StackADT.java public interface StackADT<T> { /** Adds one element to the top of this stack. * @param element element to be pushed onto stack */ public void push (T element);    /** Removes and returns the top element from this stack. * @return T element removed from the top of the stack */ public T pop(); /** Returns without removing the top element of this stack. * @return T...

  • answer the questions throughout this program public class Day implements Comparable {    Private Boolean atWork;...

    answer the questions throughout this program public class Day implements Comparable {    Private Boolean atWork;    Private String Weather;    Private int fuNumber; } public Day ( boolean Atwork, String Weather, int funNumber) {    Atwork = Atwork;    Weather = Weather;    funNumber = funNumber; } //question 1: implement the getter and setter (mutatto of the funNumber data member. if the number is outside the range 0-10 make the fuNumebr=5; public boolean equals (Day rhs) {    //...

  • Java Programming: The following is my code: import java.util.Arrays; public class KWArrayList<E> {    // Data...

    Java Programming: The following is my code: import java.util.Arrays; public class KWArrayList<E> {    // Data fields    /** The default initial capacity */    private static final int INITIAL_CAPACITY = 10;       /** The underlying data array */    private E[] theData;       /** The current size */    private int size = 0;       /** The current capacity */    private int capacity = 0;       @SuppressWarnings("unchecked")    public KWArrayList() {        capacity...

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