Question

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 stack
// time: O(1)
// space: O(1)
public int pop()
{
if(head==null)
return -1;
size--;
int value=head.data;
head=head.next;
return value;
}

//Input = none
//Output = top of stack or last value added to stack
// method returns top of stack
// time: O(1)
// space: O(1)
public int peek()
{
if(head==null)
return -1;
return head.data;
}

//Input = none
//Output = true or false depending on if head is null or not
// method that says whether the stack is empty or not
// time: O(1)
// space: O(1)
public boolean isEmpty()
{
return head==null;
}

//Input = none
//Output = int representing number of elements in stack
// method that returns the size of stack
// time: O(1)
// space: O(1)
public int size()
{
return size;
}
}

class Node
{
int data;
Node next;
Node(int data)
{
this.data=data;
this.next=null;
}
}

class QueuesFromStacks
{
Stack s1,s2;

QueuesFromStacks() // constructor initializes two stacks
{
s1=new Stack();
s2=new Stack();
}

//Input = send in and int representing the value to be added
//Output = none; element just added to list
// method that enqueues value into queue. Here we just add push the value into s1
// time: O(1)
// space: O(1)
public void enqueue(int value)
{
s1.push(value);
}

//Input = none;
//Output = number from front of queue or first added number
// method that dequeues value from queue.
// time: O(n)
// space: O(1)
public int dequeue()
{
if(isEmpty())
return -1;
if(!s2.isEmpty())
{
int value=s2.pop();
return value;
}
while(!s1.isEmpty())
s2.push(s1.pop());
int value=s2.pop();
return value;
}

//Input = none;
//Output = returns element in front of list without removing it
// method that returns the top most value of queue
// time: O(n)
// space: O(1)
public int peek()
{
if(isEmpty())
return -1;
if(!s2.isEmpty())
return s2.peek();
while(!s1.isEmpty())
s2.push(s1.pop());
return s2.peek();
}

//Input = none
//Output = true or false depending on if empty
// method that says whether the queue is empty or not
// time: O(1)
// space: O(1)
public boolean isEmpty()
{
return s1.isEmpty() && s2.isEmpty();
}

//Input = none
//Output = total size (which must add both stacks)
// method that returns size of queue
// time: O(1)
// space: O(1)
public int size()
{
return s1.size()+s2.size();
}
}
class Main
{

public static void main(String args[])
{
QueuesFromStacks queueTest =new QueuesFromStacks();
for(int i=1;i<=5;i++)
queueTest.enqueue(i);
while(!queueTest.isEmpty())
System.out.print(queueTest.dequeue()+" ");
System.out.println();
}
}

****************************************************************

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

Hi. I have answered the same question (QueuesFromStacks) before. Here is the completed code for this problem. 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. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks

Make sure you copy below classes into separate files as mentioned. Do not copy everything to a single file.

//QueuesFromStacks.java

public class QueuesFromStacks<E> {

      // declaring two stacks. please find Stack.java at the end of this code.

      private Stack<E> s1, s2;

      // constructor initializing both stacks

      public QueuesFromStacks() {

            s1 = new Stack<E>();

            s2 = new Stack<E>();

      }

      // adds an element to the end of the queue

      public void enqueue(E item) {

            // moving all elements from s1 to s2

            while (!s1.isEmpty()) {

                  s2.push(s1.pop());

            }

            // adding item to s1

            s1.push(item);

            // moving all items from s2 back into s1

            while (!s2.isEmpty()) {

                  s1.push(s2.pop());

            }

      }

      // removes and returns front element

      public E dequeue() {

            if (isEmpty()) {

                  return null;

            }

            return s1.pop();

      }

      // returns front element

      public E peek() {

            if (isEmpty()) {

                  return null;

            }

            return s1.peek();

      }

      // returns true if stack is empty, false if not

      public boolean isEmpty() {

            return size() == 0;

      }

      // returns the size

      public int size() {

            return s1.size();

      }

      // main method for testing, you may move this into Main.java class if you want.

      public static void main(String[] args) {

            // creating a queue of integers, adding numbers from 1 to 5

            QueuesFromStacks<Integer> q = new QueuesFromStacks<Integer>();

            for (int i = 1; i <= 5; i++) {

                  q.enqueue(i);

            }

            // dequeuing 3 values and displaying

            System.out.println(q.dequeue()); // 1

            System.out.println(q.dequeue()); // 2

            System.out.println(q.dequeue()); // 3

            // adding 6

            q.enqueue(6);

            System.out.println(q.dequeue()); // 4

            // adding 7

            q.enqueue(7);

            // removing and displaying remaining values. should print values fro 5

            // to 7

            while (!q.isEmpty()) {

                  System.out.println(q.dequeue());

            }

      }

}

//Stack.java

public class Stack<E> {

      private Node<E> top;

      private int size;

      public Stack() {

            top = null;

            size = 0;

      }

     

      //adds an element to the top

      public void push(E element) {

            Node<E> n = new Node<E>(element);

            n.next = top;

            top = n;

            size++;

      }

     

      //removes and returns top element

      public E pop() {

            if (isEmpty()) {

                  return null;

            }

            E item = top.item;

            top = top.next;

            size--;

            return item;

      }

     

      //returns top element

      public E peek() {

            if (isEmpty()) {

                  return null;

            }

            return top.item;

      }

      // returns true if queue is empty, false if not

      public boolean isEmpty() {

            // queue is empty if front is null

            return size == 0;

      }

     

      //returns the size

      public int size() {

            return size;

      }

      // a class to represent the Node

      class Node<E> {

            // making data and next fields public, so that we can easily access them

            // without methods

            public E item;

            public Node<E> next;

            // constructor taking initial value for data

            public Node(E d) {

                  item = d;

                  next = null;

            }

      }

}

/*OUTPUT*/

1

2

3

4

5

6

7

Add a comment
Know the answer?
Add Answer to:
how do I change my code to generic form *********************************************************************** public class UnboundedStackQueue { //question#3 }...
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 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...

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

  • I was told I need three seperate files for these classes is there anyway to tie...

    I was told I need three seperate files for these classes is there anyway to tie all these programs together into one program after doing that. I'm using netbeans btw. import java.util.ArrayList; import java.util.Scanner; /** * * */ public class MySorts {       public static void main(String[] args) {             Scanner input = new Scanner(System.in);             String sentence;             String again;             do {                   System.out                               .println("Enter a sentence, I will tell you if it is a palindrome: ");...

  • On java create the following: please solve it complete or don't since it considered as part...

    On java create the following: please solve it complete or don't since it considered as part of problem 1 not even the whole question. The main method that does: Create 2 stacks s1 and s2 Insert 23 integers between 20 and 60 (do not insert duplicates) into s1 Insert 35 integers between 10 and 80 (do not insert duplicates) into s2. Give the user the choice which methods (2-7) to call and option to exit LinkedList<Integer> LL = new LinkedList<Integer>)...

  • JAVA LANG PLEASE: I have follwed these below guidelines but when i run my queue test...

    JAVA LANG PLEASE: I have follwed these below guidelines but when i run my queue test it is not executing but my stack is working fine, can you fix it please! MyQueue.java Implement a queue using the MyStack.java implementation as your data structure.  In other words, your instance variable to hold the queue items will be a MyStack class. enqueue(String item): inserts item into the queue dequeue(): returns and deletes the first element in the queue isEmpty(): returns true or false...

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

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

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

  • Are based on the following Queue class code segment class QueueFull {/* Empty exception class */};...

    Are based on the following Queue class code segment class QueueFull {/* Empty exception class */}; Class Queue Empty {/* Empty exception class */}; struct Node//Node structure int data;//Holds an integer Node* next;//Pointer to next node in the queue}; Class Queue//Linked node implementation of Queue ADT {Private: Node* front;//Pointer to front node of queue Node* rear;//pointer to last node of queue Public: Queue ()://default constructor initializes queue to be empty -Queue ();//Deallocates all nodes in the queue Void Add (int...

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