In: Computer Science
Question 1
Refer to the operations below:
Add (10 + 5)
Add (4+8)
Add (7*2)
Add (90 – 3)
Print list
Print peek
Remove an item from the list
Print list
1.1 Implement the operations above into a Queue structure called
q1.
1.2 Implement the operations above into a Stack structure called
s1.
Name your program Question1_1 for the queue structure and Question1_2 for the stack structure
JAVA Language to be used.
Please give step by step explanation on how to save and run the programs
In Java, we have available data structures for queue and stack.
1. Using Queue data structure.
- Create a file named Question1_1.java and add below code into it.
import java.util.*;
public class Question1_1 {
public static void main(String[] args) {
//We can't create instance of a Queue since it is an interface
Queue<Integer> q1 = new LinkedList<Integer>();
//Adding elements to the Queue
//it will add 15
q1.add(10+5);
//it will add 12
q1.add(4+8);
//it will add 14
q1.add(7*2);
//it will add 87
q1.add(90-3);
//to print a list
System.out.println("List :"+q1);
//peek() method - it returns the head of queue and null if list is empty
System.out.println("peek(): "+q1.peek());
//remove() - it will remove first element from queue
System.out.println("Removed element: "+q1.remove());
//to print a list
System.out.println("List :"+q1);
}
}
Save your file and in cmd, go to the directory where you saved your program Question1_1.java
Type javac Question1_1.java and press enter to compile you code. If there is no errors in your code, It will take to next line
Now type java Question1_1.java to run your program and you can see the output on cmd window.
You can refer this screenshots for indentation and output of the code
Output :
2. Using a stack
Create a file named Question1_2.java and add below code into it.
import java.util.*;
public class Question1_2 {
public static void main(String[] args) {
//create instance of a Stack as s1
Stack<Integer> s1 = new Stack<Integer>();
//Adding elements to the Stack using push method
//it will add 15
s1.push(10+5);
//it will add 12
s1.push(4+8);
//it will add 14
s1.push(7*2);
//it will add 87
s1.push(90-3);
//to print a list
System.out.println("List :"+s1);
//peek() method - it returns the top of stack and null if stack is empty
System.out.println("peek(): "+s1.peek());
//pop() - it will remove top element from stack
System.out.println("Removed element: "+s1.pop());
//to print a list
System.out.println("List :"+s1);
}
}
Save your file and in cmd, go to the directory where you saved your program Question1_2.java
Type javac Question1_2.java and press enter to compile you code. If there is no errors in your code, It will take to next line
Now type java Question1_2.java to run your program and you can see the output on cmd window.
You can refer this screenshots for indentation and output of the code
Output :
NOTE : make sure that you have set path variable to run java code in your system.