1 answer

Implement a class for a stack and a queue. Implement as a parent a superclass called...

Question:

Implement a class for a stack and a queue. Implement as a parent a superclass called “ Container and two subclasses called “ Stack and Queue” How would you use templates on these classes to make in generic?

please I need step by step


Answers

class Node<T>{
   T data;
   Node<T> next;
   Node(T val){
       this.data=val;
       this.next=null;
   }
}
class Container<T>{
   Node<T> n;
   Container(){
       this.n=null;
   }
  
}
class Queue<T> extends Container<T>{
  
   Node<T> front, rear;
  
    public Queue() {
        this.front = this.rear = null;
    }
     
    // Method to add an key to the queue.
    void enqueue(T key)
    {
        
        Node<T> temp = new Node<T>(key);
    
        if (this.rear == null)
        {
           this.front = this.rear = temp;
           return;
        }
     
        this.rear.next = temp;
        this.rear = temp;
    }
     
    // Method to remove an key from queue.
    Node<T> dequeue()
    {
        //return null if queue is empty
        if (this.front == null)
           return null;
     
        // Store previous front and move front one node ahead
        Node<T> temp = this.front;
        this.front = this.front.next;
     
        // If front becomes NULL, then change rear also as NULL
        if (this.front == null)
           this.rear = null;
       // System.out.println(temp);
        return temp;
    }
  
}
class Stack<T> extends Container<T>{
   Node<T> Top;
   Stack(){
       this.Top=null;
   }
  
   //Function to check stack is empty or not
    public boolean isEmpty()
    {
        return this.Top == null;
    }
    //Function to get the top element in stack
    public Node<T> peek()
    {
        // check for empty stack
        if (!isEmpty()) {
            return this.Top;
        }
        else {
            System.out.println("Stack is empty");
            return null;
        }
    }
   public void push(T x) // insert at the beginning
    {
        // create a temp node
        Node<T> temp = new Node<T>(x);

        //if heap is not full insert the node
        if (temp != null) {
            temp.next = Top;
            Top = temp;
          
        } else {
           System.out.println("\nOverflow!!!!!! Can't insert into stack");
        }
     
    }
    // Function to pop top element from the stack
    public void pop() {
        // check for stack underflow
        if (Top != null) {
           Top = Top.next;
         
        } else {
           System.out.println("\nUnderflow!!!!!! Cant pop element from stack");
        }
    }
}
//main class to test queue and stack
public class TemplateClass {

   public static void main(String[] args) {
       //creating queue object
       Queue<Integer> q1=new Queue<Integer>();
       q1.enqueue(4);
       q1.enqueue(6);
       q1.enqueue(1);
       System.out.println(q1.dequeue().data);
      
       //creating stack object
       Stack<Character> s1=new Stack<Character>();
       s1.push('d');
       s1.push('a');
       s1.push('i');
       System.out.println(s1.peek().data);

   }

}


//############################### PGM END #############################
OUTPUT
##########

<terminated> Templat 4 1

.

Similar Solved Questions

1 answer
14.3 Problem 14.3 Part A An air-track glider is attached to a spring. The glider is...
14.3 Problem 14.3 Part A An air-track glider is attached to a spring. The glider is pulled to the right and released from rest at t-0 s. It then oscillates with a period of 2.40 s and a maximum speed of 30.0 cm/s What is the amplitude of the oscillation? Express your answer with the appropriate unit...
1 answer
2. Suppose that we are using a box-and-whisker plot to depict a population or sample of...
2. Suppose that we are using a box-and-whisker plot to depict a population or sample of measurements. How would you interpret each of the following. (a) The whisker to the right is much longer than the whisker to the left. [2 marks] (b) The interquartile range is much longer than either of the whisk...
1 answer
4. Find the orthogonal decomposition of v with respect to W A. 1 1 V= 4...
4. Find the orthogonal decomposition of v with respect to W A. 1 1 V= 4 -2 3 ,W = span 2 :1) 7 1 B. 2 1 1 1 0 V = W = span (0 5 6 0 1...
1 answer
A random sample of 25 observations was selected from a normally distributed population. The average in the sample was 84.6 with a variance of 400.
1. A random sample of 25 observations was selected from a normally distributed population. The average in the sample was 84.6 with a variance of 400.a. Construct a 90% confidence interval for μ.b. Construct a 99% confidence interval for μ.c. Discuss why the 90% and 99% confidence intervals are...
1 answer
1. You are considering a project that needs $50,000 investment to start. This is a 5 year project and you are expecting...
1. You are considering a project that needs $50,000 investment to start. This is a 5 year project and you are expecting that the project generates annual cash flows after taxes of $10,000, $50,000, $90,000, $20,000 and -$30,000 respectively. What is the NPV of this project if the required rate of re...
1 answer
One of the Baldrige Core Values is Patient-Focused Excellence. The description on pages 40-41 of the...
One of the Baldrige Core Values is Patient-Focused Excellence. The description on pages 40-41 of the Baldrige Excellence Framework document suggests numerous activities on which an excellent organization should focus to achieve patient-focused excellence, which I have extracted below (many of these ...
1 answer
How do I find values of Θ between 0 and 2π that satisfy -1 - 3 sin Θ = cos 2Θ ??
How do I find values of Θ between 0 and 2π that satisfy -1 - 3 sin Θ = cos 2Θ ??...
1 answer
6.Assertions about classes of transactions and events typically include _______. A. occurrence, cutoff, and completeness B....
6.Assertions about classes of transactions and events typically include _______. A. occurrence, cutoff, and completeness B. existence, rights, and obligations C. existence, rights, and cutoff D. completeness, accuracy, and valuation...
1 answer
Convert the E/R diagram into a relational schema. seats row Bookings toCust toFit Flights Customers aircraft...
Convert the E/R diagram into a relational schema. seats row Bookings toCust toFit Flights Customers aircraft addr SIN day phone number name...
1 answer
Shown below is two MOS transistors in series. Assuming the transistors have the same threshold voltage, and that Vos is...
Shown below is two MOS transistors in series. Assuming the transistors have the same threshold voltage, and that Vos is large enough, argue in which region of operation Mi and M2 are. a. b. Show that for the equivalent transistor, B- Assume both transistors are square-law, and ignore channel length ...
1 answer
Which of the following statements is FALSE? A. The addition of phosphorus to polluted coastal ecosystems...
Which of the following statements is FALSE? A. The addition of phosphorus to polluted coastal ecosystems often results in reduced growth of phytoplankton. B. Shallow marine waters have higher productivity partly because nutrients are easily transported from benthic habitats to surface wate...
1 answer
Question 3 Two employees, Alice and Bart, work at a cell phone retailer. They are paid...
Question 3 Two employees, Alice and Bart, work at a cell phone retailer. They are paid partially on commission and get paid every two weeks. Over the course of a year they both earn the same amount of income (same mean) but Alice has a higher variance in her pay. 1. Would you prefer to have higher v...
1 answer
(4) A cyanide ion-selective electrode obeys the equation, E-K-0.05916log(CN). The potential was - 0.230 V when...
(4) A cyanide ion-selective electrode obeys the equation, E-K-0.05916log(CN). The potential was - 0.230 V when the electrode was immersed in 1.00 mM NaCN. (a) Evaluate the constant in the equation (b) Using the result from part (a), find (CN) if E=-0.280 V. (c) Without using the constant from part (...
1 answer
O stop taking any depreciation on the machine. Change from the general MACRS to a straight-line...
O stop taking any depreciation on the machine. Change from the general MACRS to a straight-line system. Recapture a prorated portion of that which was expensed. O Change nothing. □Mark for follow up Question 34 of 75 Marcela is a sole proprietor and wishes to use the actual method for business...
1 answer
Part 1,2 and 3 004 (part 1 of 3) 10.0 points A 0.657 kg particle has...
Part 1,2 and 3 004 (part 1 of 3) 10.0 points A 0.657 kg particle has a speed of 2.6 m/s at point A and kinetic energy of 7 J at point B. What is its kinetic energy at A? Answer in units of J. 005 (part 2 of 3) 10.0 points What is the particle's speed at B? Answer in units of m/s. 006 (part 3 ...
2 answers
A lottery game has balls numbered from 0 - 9 If a ball is selected at random, what is the probability of selecting an even numbered ball or a 5
A lottery game has balls numbered from 0 - 9 If a ball is selected at random, what is the probability of selecting an even numbered ball or a 5 ?I am guessing this is Mutually exclusive event and hence used the OR= P(A)+P(B) conceptconsidering 0 as an even number I keep getting 1 as an answer..help ...
1 answer
/Chem%20210% Imported From Sa. 3. A compound is analyzed and found to contain 65.4% C, 5,5%...
/Chem%20210% Imported From Sa. 3. A compound is analyzed and found to contain 65.4% C, 5,5% H, and 29.1% O by mass. In a separate experiment, the compound is found to effuse through an opening at a rate of 3.0 x 10 mol/min. A sample of neon gas effused through the same opening at a rate of 7.0 x 10 ...