SlideShare a Scribd company logo
In java , I want you to implement a Data Structure known as a Doubly-Ended-Queue. it is a
“fair” data structure in that it implements a FIFO (First In First Out ) behavior. As such, it is
often used to implement various wait lists in computer systems. For example, jobs waiting to use
the CPU, jobs waiting for a printer, jobs waiting to be placed into RAM for execution. In short,
whenever we want a fair strategy for waiting we use queues.
A DEQUE (Doubly-ended-queue) is a related data structure. Although similar to a Queue, it
differs in that it allows for insertions AND deletions from either end of the list (both the front
and the rear).
Your implementation MUST use a doubly-linked-list implementation. You may not use a static
array implementation.
Thus, a Deque is a List but it is one which only concerns itself with the first and last positions for
any insertion or deletion. The 6 operations supported are :
public void insertFront( int item ) - insert the given item (as a node) into the first position of the
Deque.
public void insertRear( int item ) - insert the given item (as a node) into the last position of the
Deque.
public int deleteFront( ) - delete and return the element stored in the first node of the Deque.
public int deletRear( ) – delete and return the element stored in the last node of the Deque.
public boolean isempty( ) - returns true if the Deque is currently empty or false if it is not.
public void printDeque( ) - print the integers from the list, one per line, from the first element
through to the last in order.
Classes
Your program must implement the following 3 classes. public class dequeDriver
This class will contain your program’s main method. It will need to declare a deque object and
process input as indicated below.
Your program should prompt the user for the path of an input file. It should open the file for
input and process it line by line. Each line of the input file will have one of the following forms.
PR
IF
IR
DF
DR
The meanings of each input is as follows:
PR - print the current contents of the deque from front to rear using the printDeque( ) method of
the deque object.
IF - insert the given int value into the front of the deque.
IR - insert the given int value into the rear of the deque.
DF - delete the front value from the deque.
DR – delete the rear element of the deque.
Below is an example input file that your program should be able to process.
PR
IF 4
IF 5
IF 6
IR 7
PR
DR
PR
DF
PR
The output for the input file shown above is :
EMPTY DEQUE
----- Front -----
6
5
4
7
----- Rear -----
----- Front -----
6
5
4
----- Rear -----
----- Front -----
5
4
----- Rear -----
public class dequeNode
This class will implement the linked nodes that will be used to implement the deque itself.
It should have the following protected data members.
protected dequeNode next; // next pointer to next node
protected dequeNode prev; // previous pointer to previous node
protected int val; // the integer value stored within the dequeNode.
The following methods should be supported :
public dequeNode getNext( ) - return the next field of the current dequeNode.
public dequeNode getPrev( ) – return the prev field of the current dequeNode.
public void setNext( dequeNode n ) – set the next field of the current dequeNode to n.
public void setPrev( dequeNode p ) – set the prev field of the current dequenode to p.
public int getVal( ) - simply returns the integer value stored in the val field.
The class should also have a constructor that expects an integer argument which will be placed
into the integer field val.
public dequeNode( int v )
public class deque
This is the actual deque structure. It will consist of a variable of type dequeNode named elts.
protected dequeNode elts; // the pointer to the first element in deque.
The class will need a default constructor which takes no arguments and sets the dequeNode elts
to null.
public deque( ) - set elts member to null for empty deque
The other methods are as described earlier….
public void insertFront( int item ) - insert the given item (as a node) into the first position of the
Deque.
public void insertRear( int item ) - insert the given item (as a node) into the last position of the
Deque.
public int deleteFront( ) - delete and return the element stored in the first node of the Deque.
public int deletRear( ) – delete and return the element stored in the last node of the Deque.
public boolean isempty( ) - returns true if the Deque is currently empty or false if it is not.
public void printDeque( ) - print the integers from the list, one per line, from the first element
through to the last in order.
Solution
import java.io.File;
import java.util.Scanner;
import java.util.ArrayList;
public class DequeDriver {
public static void main(String[] args) {
// Will read a .txt file of valid commands and perform them on a deque.
Deque deque = new Deque();
Scanner input = new Scanner(System.in);
System.out.println("Please enter a file path: " );
try {
Scanner fileReader = new Scanner(new File(input.nextLine()));
ArrayList commands = new ArrayList<>();
while (fileReader.hasNextLine()) {
commands.add(fileReader.nextLine());
}
for (int i = 0; i < commands.size(); i++) {
if (commands.get(i).equals("PR")) {
if (deque.isempty()) {
System.out.println("EMPTY DEQUE");
}
else {
System.out.println("-----Front-----");
deque.printDeque();
System.out.println("-----Rear-----");
}
}
if (commands.get(i).substring(0, 2).equals("IR")) {
deque.insertRear(Integer.parseInt(commands.get(i).substring(3,commands.get(i).length())));
}
if (commands.get(i).substring(0, 2).equals("IF")) {
deque.insertFront(Integer.parseInt(commands.get(i).substring(3,commands.get(i).length())));
}
if (commands.get(i).equals("DF")) {
deque.deleteFront();
}
if (commands.get(i).equals("DR")) {
deque.deleteRear();
}
}
fileReader.close();
}
catch (Exception e) { // Deque methods are secure, so any exception thrown will be from
input.
System.out.println("Sorry, your input was invalid. Try running again with different
input.");
e.printStackTrace();
input.close();
return;
}
input.close();
}
}
Deque.java
public class Deque {
private DequeNode elts; // The pointer to the first element in the deque
public void deque( ) { // Set elts member to null for empty deque
elts = null;
}
public void insertFront( int item ) {
// Insert the given item (as a node) into the first position of the Deque.
DequeNode node = new DequeNode(item);
if (this.isempty()) // Test for empty deque
elts = node;
else {
DequeNode temp = elts;
elts = node;
elts.setNext(temp);
if (temp.getPrev() == null) { // Test for deque with one item
elts.setPrev(temp);
temp.setNext(elts);
}
else {
elts.setPrev(temp.getPrev());
temp.getPrev().setNext(elts);
}
temp.setPrev(elts);
}
}
public void insertRear( int item ) {
// Insert the given item (as a node) into the last position of the Deque.
DequeNode node = new DequeNode(item);
if (this.isempty()) // Test for empty deque
elts = node;
else {
node.setNext(elts);
if (elts.getPrev() == null) { // Test for deque with one item
node.setPrev(elts);
elts.setNext(node);
}
else {
DequeNode temp = elts.getPrev();
node.setPrev(temp);
temp.setNext(node);
}
elts.setPrev(node);
}
}
public int deleteFront( ) {
// Delete and return the element stored in the first node of the Deque.
if (!this.isempty()) {
int val = elts.getVal();
if (elts.getPrev() == null) // If there's only 1 item, just delete it.
elts = null;
else {
elts.getPrev().setNext(elts.getNext());
elts.getNext().setPrev(elts.getPrev());
elts = elts.getNext();
}
return val;
}
else {
System.out.println("Deque is empty! Returning 0...");
return 0;
}
}
public int deleteRear( ) {
// Delete and return the element stored in the last node of the Deque.
if (!this.isempty()) {
int val;
if (elts.getPrev() == null) { // If there's only 1 item, just delete it.
val = elts.getVal();
elts = null;
return val;
}
else {
val = elts.getPrev().getVal();
DequeNode oldRear = elts.getPrev();
oldRear.getPrev().setNext(elts);
elts.setPrev(oldRear.getPrev());
return val;
}
}
else {
System.out.println("Deque is empty! Returning 0...");
return 0;
}
}
public boolean isempty( ) {
// Returns true if the Deque is currently empty or false if it is not.
return (elts == null);
}
public void printDeque( ) {
// Print the integers from the list, one per line, from the first element through to the last in
order.
if (this.isempty())
System.out.println("EMPTY DEQUE");
else {
DequeNode index = elts;
System.out.println(elts.getVal());
if (index.getNext() != null) {
index = index.getNext();
while (index != elts) {
System.out.println(index.getVal());
index = index.getNext();
}
}
}
}
}
DequeNode.java
package program1;
public class DequeNode {
protected DequeNode next; // Next pointer to next node
protected DequeNode prev; // Previous pointer to previous node
protected int val; // The integer value stored within the dequeNode.
public DequeNode() {
}
public DequeNode(int val) {
this.val = val;
}
public DequeNode getNext( ) { // Return the next field of the current dequeNode.
return next;
}
public DequeNode getPrev( ) { // Return the prev field of the current dequeNode.
return prev;
}
public void setNext( DequeNode n ) { // Set the next field of the current dequeNode to n.
next = n;
}
public void setPrev( DequeNode p ) { // Set the prev field of the current dequenode to p.
prev = p;
}
public int getVal( ) { // Simply returns the integer value stored in the val field.
return val;
}
}

More Related Content

Similar to In java , I want you to implement a Data Structure known as a Doubly.pdf

Lab02kdfshdfgajhdfgajhdfgajhdfgjhadgfasjhdgfjhasdgfjh.pdf
Lab02kdfshdfgajhdfgajhdfgajhdfgjhadgfasjhdgfjhasdgfjh.pdfLab02kdfshdfgajhdfgajhdfgajhdfgjhadgfasjhdgfjhasdgfjh.pdf
Lab02kdfshdfgajhdfgajhdfgajhdfgjhadgfasjhdgfjhasdgfjh.pdf
QalandarBux2
 
Using NetBeansImplement a queue named QueueLL using a Linked List .pdf
Using NetBeansImplement a queue named QueueLL using a Linked List .pdfUsing NetBeansImplement a queue named QueueLL using a Linked List .pdf
Using NetBeansImplement a queue named QueueLL using a Linked List .pdf
siennatimbok52331
 
Lec3
Lec3Lec3
Write a Java Class to Implement a Generic Linked ListYour list mus.pdf
Write a Java Class to Implement a Generic Linked ListYour list mus.pdfWrite a Java Class to Implement a Generic Linked ListYour list mus.pdf
Write a Java Class to Implement a Generic Linked ListYour list mus.pdf
rozakashif85
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
Apurbo Datta
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
Abhishek Tirkey
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
GauravPandey43518
 
01-intro_stacks.ppt
01-intro_stacks.ppt01-intro_stacks.ppt
01-intro_stacks.ppt
soniya555961
 
srgoc
srgocsrgoc
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
Sigma Software
 
Queue Data Structure (w/ php egs)
Queue Data Structure (w/ php egs)Queue Data Structure (w/ php egs)
Queue Data Structure (w/ php egs)
Roman Rodomansky
 
computer notes - Memory organization
computer notes - Memory organizationcomputer notes - Memory organization
computer notes - Memory organization
ecomputernotes
 
The enqueue operation on the Queue ADT adds a new item to the back of (1).docx
The enqueue operation on the Queue ADT adds a new item to the back of (1).docxThe enqueue operation on the Queue ADT adds a new item to the back of (1).docx
The enqueue operation on the Queue ADT adds a new item to the back of (1).docx
carold11
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
RAtna29
 
Standard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented ProgrammingStandard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented Programming
Mandeep Singh
 
Stack linked list
Stack linked listStack linked list
Stack linked list
bhargav0077
 
Unit i(dsc++)
Unit i(dsc++)Unit i(dsc++)
Unit i(dsc++)
Durga Devi
 
Help please!!(Include your modified DList.java source code file in.pdf
Help please!!(Include your modified DList.java source code file in.pdfHelp please!!(Include your modified DList.java source code file in.pdf
Help please!!(Include your modified DList.java source code file in.pdf
jyothimuppasani1
 
Lec3
Lec3Lec3
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
Sriram Raj
 

Similar to In java , I want you to implement a Data Structure known as a Doubly.pdf (20)

Lab02kdfshdfgajhdfgajhdfgajhdfgjhadgfasjhdgfjhasdgfjh.pdf
Lab02kdfshdfgajhdfgajhdfgajhdfgjhadgfasjhdgfjhasdgfjh.pdfLab02kdfshdfgajhdfgajhdfgajhdfgjhadgfasjhdgfjhasdgfjh.pdf
Lab02kdfshdfgajhdfgajhdfgajhdfgjhadgfasjhdgfjhasdgfjh.pdf
 
Using NetBeansImplement a queue named QueueLL using a Linked List .pdf
Using NetBeansImplement a queue named QueueLL using a Linked List .pdfUsing NetBeansImplement a queue named QueueLL using a Linked List .pdf
Using NetBeansImplement a queue named QueueLL using a Linked List .pdf
 
Lec3
Lec3Lec3
Lec3
 
Write a Java Class to Implement a Generic Linked ListYour list mus.pdf
Write a Java Class to Implement a Generic Linked ListYour list mus.pdfWrite a Java Class to Implement a Generic Linked ListYour list mus.pdf
Write a Java Class to Implement a Generic Linked ListYour list mus.pdf
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
 
01-intro_stacks.ppt
01-intro_stacks.ppt01-intro_stacks.ppt
01-intro_stacks.ppt
 
srgoc
srgocsrgoc
srgoc
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 
Queue Data Structure (w/ php egs)
Queue Data Structure (w/ php egs)Queue Data Structure (w/ php egs)
Queue Data Structure (w/ php egs)
 
computer notes - Memory organization
computer notes - Memory organizationcomputer notes - Memory organization
computer notes - Memory organization
 
The enqueue operation on the Queue ADT adds a new item to the back of (1).docx
The enqueue operation on the Queue ADT adds a new item to the back of (1).docxThe enqueue operation on the Queue ADT adds a new item to the back of (1).docx
The enqueue operation on the Queue ADT adds a new item to the back of (1).docx
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
 
Standard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented ProgrammingStandard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented Programming
 
Stack linked list
Stack linked listStack linked list
Stack linked list
 
Unit i(dsc++)
Unit i(dsc++)Unit i(dsc++)
Unit i(dsc++)
 
Help please!!(Include your modified DList.java source code file in.pdf
Help please!!(Include your modified DList.java source code file in.pdfHelp please!!(Include your modified DList.java source code file in.pdf
Help please!!(Include your modified DList.java source code file in.pdf
 
Lec3
Lec3Lec3
Lec3
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 

More from aromalcom

One goal of EHRs is to facilitate providers’ sharing of clinical inf.pdf
One goal of EHRs is to facilitate providers’ sharing of clinical inf.pdfOne goal of EHRs is to facilitate providers’ sharing of clinical inf.pdf
One goal of EHRs is to facilitate providers’ sharing of clinical inf.pdf
aromalcom
 
Mutations during which of the following processes in animals will af.pdf
Mutations during which of the following processes in animals will af.pdfMutations during which of the following processes in animals will af.pdf
Mutations during which of the following processes in animals will af.pdf
aromalcom
 
Let E, F and G be three sets. State expressions for the eventsonl.pdf
Let E, F and G be three sets. State expressions for the eventsonl.pdfLet E, F and G be three sets. State expressions for the eventsonl.pdf
Let E, F and G be three sets. State expressions for the eventsonl.pdf
aromalcom
 
In humans, the sickle-cell trait is caused by a single detective alle.pdf
In humans, the sickle-cell trait is caused by a single detective alle.pdfIn humans, the sickle-cell trait is caused by a single detective alle.pdf
In humans, the sickle-cell trait is caused by a single detective alle.pdf
aromalcom
 
Identify three examples of how U.S. society is heteronormative.S.pdf
Identify three examples of how U.S. society is heteronormative.S.pdfIdentify three examples of how U.S. society is heteronormative.S.pdf
Identify three examples of how U.S. society is heteronormative.S.pdf
aromalcom
 
How the U.S. Banking Structure Compares to the Rest of the WorldFo.pdf
How the U.S. Banking Structure Compares to the Rest of the WorldFo.pdfHow the U.S. Banking Structure Compares to the Rest of the WorldFo.pdf
How the U.S. Banking Structure Compares to the Rest of the WorldFo.pdf
aromalcom
 
Human cells contain two different types of genes. Most of our genes a.pdf
Human cells contain two different types of genes. Most of our genes a.pdfHuman cells contain two different types of genes. Most of our genes a.pdf
Human cells contain two different types of genes. Most of our genes a.pdf
aromalcom
 
Growth of Bacteria Bacteria grown in a laboratory are inoculated .pdf
Growth of Bacteria Bacteria grown in a laboratory are inoculated .pdfGrowth of Bacteria Bacteria grown in a laboratory are inoculated .pdf
Growth of Bacteria Bacteria grown in a laboratory are inoculated .pdf
aromalcom
 
Businesses combine for many reasons. The rationale for combining som.pdf
Businesses combine for many reasons. The rationale for combining som.pdfBusinesses combine for many reasons. The rationale for combining som.pdf
Businesses combine for many reasons. The rationale for combining som.pdf
aromalcom
 
C++ Programming (Please help me!! Thank you!!)Problem A Win SimU.pdf
C++ Programming (Please help me!! Thank you!!)Problem A Win SimU.pdfC++ Programming (Please help me!! Thank you!!)Problem A Win SimU.pdf
C++ Programming (Please help me!! Thank you!!)Problem A Win SimU.pdf
aromalcom
 
You dont know the length, the width is four feet less than twice t.pdf
You dont know the length, the width is four feet less than twice t.pdfYou dont know the length, the width is four feet less than twice t.pdf
You dont know the length, the width is four feet less than twice t.pdf
aromalcom
 
A polypeptide chain contains an amphipathic helix, with arginine and.pdf
A polypeptide chain contains an amphipathic helix, with arginine and.pdfA polypeptide chain contains an amphipathic helix, with arginine and.pdf
A polypeptide chain contains an amphipathic helix, with arginine and.pdf
aromalcom
 
9. Elaborate why materials have tendency to be corrodedSolution.pdf
9. Elaborate why materials have tendency to be corrodedSolution.pdf9. Elaborate why materials have tendency to be corrodedSolution.pdf
9. Elaborate why materials have tendency to be corrodedSolution.pdf
aromalcom
 
5. What are the main factors that affect the demand for the following.pdf
5. What are the main factors that affect the demand for the following.pdf5. What are the main factors that affect the demand for the following.pdf
5. What are the main factors that affect the demand for the following.pdf
aromalcom
 
1. Research Topic Research the problem of livelock in a networked e.pdf
1. Research Topic Research the problem of livelock in a networked e.pdf1. Research Topic Research the problem of livelock in a networked e.pdf
1. Research Topic Research the problem of livelock in a networked e.pdf
aromalcom
 
While George travels for two months, Mary agrees to house and care f.pdf
While George travels for two months, Mary agrees to house and care f.pdfWhile George travels for two months, Mary agrees to house and care f.pdf
While George travels for two months, Mary agrees to house and care f.pdf
aromalcom
 
What law mandate SMEs in Ghana; Small and Medium-size Enterprises to.pdf
What law mandate SMEs in Ghana; Small and Medium-size Enterprises to.pdfWhat law mandate SMEs in Ghana; Small and Medium-size Enterprises to.pdf
What law mandate SMEs in Ghana; Small and Medium-size Enterprises to.pdf
aromalcom
 
What is the leader’s role when a substitute such as a routine job an.pdf
What is the leader’s role when a substitute such as a routine job an.pdfWhat is the leader’s role when a substitute such as a routine job an.pdf
What is the leader’s role when a substitute such as a routine job an.pdf
aromalcom
 
What function is associated with skeletal muscle cellsA. Some can.pdf
What function is associated with skeletal muscle cellsA. Some can.pdfWhat function is associated with skeletal muscle cellsA. Some can.pdf
What function is associated with skeletal muscle cellsA. Some can.pdf
aromalcom
 
What is ATP and how does it work Using what youve learned about c.pdf
What is ATP and how does it work  Using what youve learned about c.pdfWhat is ATP and how does it work  Using what youve learned about c.pdf
What is ATP and how does it work Using what youve learned about c.pdf
aromalcom
 

More from aromalcom (20)

One goal of EHRs is to facilitate providers’ sharing of clinical inf.pdf
One goal of EHRs is to facilitate providers’ sharing of clinical inf.pdfOne goal of EHRs is to facilitate providers’ sharing of clinical inf.pdf
One goal of EHRs is to facilitate providers’ sharing of clinical inf.pdf
 
Mutations during which of the following processes in animals will af.pdf
Mutations during which of the following processes in animals will af.pdfMutations during which of the following processes in animals will af.pdf
Mutations during which of the following processes in animals will af.pdf
 
Let E, F and G be three sets. State expressions for the eventsonl.pdf
Let E, F and G be three sets. State expressions for the eventsonl.pdfLet E, F and G be three sets. State expressions for the eventsonl.pdf
Let E, F and G be three sets. State expressions for the eventsonl.pdf
 
In humans, the sickle-cell trait is caused by a single detective alle.pdf
In humans, the sickle-cell trait is caused by a single detective alle.pdfIn humans, the sickle-cell trait is caused by a single detective alle.pdf
In humans, the sickle-cell trait is caused by a single detective alle.pdf
 
Identify three examples of how U.S. society is heteronormative.S.pdf
Identify three examples of how U.S. society is heteronormative.S.pdfIdentify three examples of how U.S. society is heteronormative.S.pdf
Identify three examples of how U.S. society is heteronormative.S.pdf
 
How the U.S. Banking Structure Compares to the Rest of the WorldFo.pdf
How the U.S. Banking Structure Compares to the Rest of the WorldFo.pdfHow the U.S. Banking Structure Compares to the Rest of the WorldFo.pdf
How the U.S. Banking Structure Compares to the Rest of the WorldFo.pdf
 
Human cells contain two different types of genes. Most of our genes a.pdf
Human cells contain two different types of genes. Most of our genes a.pdfHuman cells contain two different types of genes. Most of our genes a.pdf
Human cells contain two different types of genes. Most of our genes a.pdf
 
Growth of Bacteria Bacteria grown in a laboratory are inoculated .pdf
Growth of Bacteria Bacteria grown in a laboratory are inoculated .pdfGrowth of Bacteria Bacteria grown in a laboratory are inoculated .pdf
Growth of Bacteria Bacteria grown in a laboratory are inoculated .pdf
 
Businesses combine for many reasons. The rationale for combining som.pdf
Businesses combine for many reasons. The rationale for combining som.pdfBusinesses combine for many reasons. The rationale for combining som.pdf
Businesses combine for many reasons. The rationale for combining som.pdf
 
C++ Programming (Please help me!! Thank you!!)Problem A Win SimU.pdf
C++ Programming (Please help me!! Thank you!!)Problem A Win SimU.pdfC++ Programming (Please help me!! Thank you!!)Problem A Win SimU.pdf
C++ Programming (Please help me!! Thank you!!)Problem A Win SimU.pdf
 
You dont know the length, the width is four feet less than twice t.pdf
You dont know the length, the width is four feet less than twice t.pdfYou dont know the length, the width is four feet less than twice t.pdf
You dont know the length, the width is four feet less than twice t.pdf
 
A polypeptide chain contains an amphipathic helix, with arginine and.pdf
A polypeptide chain contains an amphipathic helix, with arginine and.pdfA polypeptide chain contains an amphipathic helix, with arginine and.pdf
A polypeptide chain contains an amphipathic helix, with arginine and.pdf
 
9. Elaborate why materials have tendency to be corrodedSolution.pdf
9. Elaborate why materials have tendency to be corrodedSolution.pdf9. Elaborate why materials have tendency to be corrodedSolution.pdf
9. Elaborate why materials have tendency to be corrodedSolution.pdf
 
5. What are the main factors that affect the demand for the following.pdf
5. What are the main factors that affect the demand for the following.pdf5. What are the main factors that affect the demand for the following.pdf
5. What are the main factors that affect the demand for the following.pdf
 
1. Research Topic Research the problem of livelock in a networked e.pdf
1. Research Topic Research the problem of livelock in a networked e.pdf1. Research Topic Research the problem of livelock in a networked e.pdf
1. Research Topic Research the problem of livelock in a networked e.pdf
 
While George travels for two months, Mary agrees to house and care f.pdf
While George travels for two months, Mary agrees to house and care f.pdfWhile George travels for two months, Mary agrees to house and care f.pdf
While George travels for two months, Mary agrees to house and care f.pdf
 
What law mandate SMEs in Ghana; Small and Medium-size Enterprises to.pdf
What law mandate SMEs in Ghana; Small and Medium-size Enterprises to.pdfWhat law mandate SMEs in Ghana; Small and Medium-size Enterprises to.pdf
What law mandate SMEs in Ghana; Small and Medium-size Enterprises to.pdf
 
What is the leader’s role when a substitute such as a routine job an.pdf
What is the leader’s role when a substitute such as a routine job an.pdfWhat is the leader’s role when a substitute such as a routine job an.pdf
What is the leader’s role when a substitute such as a routine job an.pdf
 
What function is associated with skeletal muscle cellsA. Some can.pdf
What function is associated with skeletal muscle cellsA. Some can.pdfWhat function is associated with skeletal muscle cellsA. Some can.pdf
What function is associated with skeletal muscle cellsA. Some can.pdf
 
What is ATP and how does it work Using what youve learned about c.pdf
What is ATP and how does it work  Using what youve learned about c.pdfWhat is ATP and how does it work  Using what youve learned about c.pdf
What is ATP and how does it work Using what youve learned about c.pdf
 

Recently uploaded

clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
Celine George
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
PECB
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
NgcHiNguyn25
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
David Douglas School District
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
TechSoup
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
heathfieldcps1
 
Top five deadliest dog breeds in America
Top five deadliest dog breeds in AmericaTop five deadliest dog breeds in America
Top five deadliest dog breeds in America
Bisnar Chase Personal Injury Attorneys
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 

Recently uploaded (20)

clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
 
Top five deadliest dog breeds in America
Top five deadliest dog breeds in AmericaTop five deadliest dog breeds in America
Top five deadliest dog breeds in America
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 

In java , I want you to implement a Data Structure known as a Doubly.pdf

  • 1. In java , I want you to implement a Data Structure known as a Doubly-Ended-Queue. it is a “fair” data structure in that it implements a FIFO (First In First Out ) behavior. As such, it is often used to implement various wait lists in computer systems. For example, jobs waiting to use the CPU, jobs waiting for a printer, jobs waiting to be placed into RAM for execution. In short, whenever we want a fair strategy for waiting we use queues. A DEQUE (Doubly-ended-queue) is a related data structure. Although similar to a Queue, it differs in that it allows for insertions AND deletions from either end of the list (both the front and the rear). Your implementation MUST use a doubly-linked-list implementation. You may not use a static array implementation. Thus, a Deque is a List but it is one which only concerns itself with the first and last positions for any insertion or deletion. The 6 operations supported are : public void insertFront( int item ) - insert the given item (as a node) into the first position of the Deque. public void insertRear( int item ) - insert the given item (as a node) into the last position of the Deque. public int deleteFront( ) - delete and return the element stored in the first node of the Deque. public int deletRear( ) – delete and return the element stored in the last node of the Deque. public boolean isempty( ) - returns true if the Deque is currently empty or false if it is not. public void printDeque( ) - print the integers from the list, one per line, from the first element through to the last in order. Classes Your program must implement the following 3 classes. public class dequeDriver This class will contain your program’s main method. It will need to declare a deque object and process input as indicated below. Your program should prompt the user for the path of an input file. It should open the file for input and process it line by line. Each line of the input file will have one of the following forms. PR IF IR DF DR The meanings of each input is as follows: PR - print the current contents of the deque from front to rear using the printDeque( ) method of the deque object.
  • 2. IF - insert the given int value into the front of the deque. IR - insert the given int value into the rear of the deque. DF - delete the front value from the deque. DR – delete the rear element of the deque. Below is an example input file that your program should be able to process. PR IF 4 IF 5 IF 6 IR 7 PR DR PR DF PR The output for the input file shown above is : EMPTY DEQUE ----- Front ----- 6 5 4 7 ----- Rear ----- ----- Front ----- 6 5 4 ----- Rear ----- ----- Front ----- 5 4 ----- Rear ----- public class dequeNode This class will implement the linked nodes that will be used to implement the deque itself. It should have the following protected data members. protected dequeNode next; // next pointer to next node
  • 3. protected dequeNode prev; // previous pointer to previous node protected int val; // the integer value stored within the dequeNode. The following methods should be supported : public dequeNode getNext( ) - return the next field of the current dequeNode. public dequeNode getPrev( ) – return the prev field of the current dequeNode. public void setNext( dequeNode n ) – set the next field of the current dequeNode to n. public void setPrev( dequeNode p ) – set the prev field of the current dequenode to p. public int getVal( ) - simply returns the integer value stored in the val field. The class should also have a constructor that expects an integer argument which will be placed into the integer field val. public dequeNode( int v ) public class deque This is the actual deque structure. It will consist of a variable of type dequeNode named elts. protected dequeNode elts; // the pointer to the first element in deque. The class will need a default constructor which takes no arguments and sets the dequeNode elts to null. public deque( ) - set elts member to null for empty deque The other methods are as described earlier…. public void insertFront( int item ) - insert the given item (as a node) into the first position of the Deque. public void insertRear( int item ) - insert the given item (as a node) into the last position of the Deque. public int deleteFront( ) - delete and return the element stored in the first node of the Deque. public int deletRear( ) – delete and return the element stored in the last node of the Deque. public boolean isempty( ) - returns true if the Deque is currently empty or false if it is not. public void printDeque( ) - print the integers from the list, one per line, from the first element through to the last in order. Solution import java.io.File; import java.util.Scanner; import java.util.ArrayList; public class DequeDriver { public static void main(String[] args) {
  • 4. // Will read a .txt file of valid commands and perform them on a deque. Deque deque = new Deque(); Scanner input = new Scanner(System.in); System.out.println("Please enter a file path: " ); try { Scanner fileReader = new Scanner(new File(input.nextLine())); ArrayList commands = new ArrayList<>(); while (fileReader.hasNextLine()) { commands.add(fileReader.nextLine()); } for (int i = 0; i < commands.size(); i++) { if (commands.get(i).equals("PR")) { if (deque.isempty()) { System.out.println("EMPTY DEQUE"); } else { System.out.println("-----Front-----"); deque.printDeque(); System.out.println("-----Rear-----"); } } if (commands.get(i).substring(0, 2).equals("IR")) { deque.insertRear(Integer.parseInt(commands.get(i).substring(3,commands.get(i).length()))); } if (commands.get(i).substring(0, 2).equals("IF")) { deque.insertFront(Integer.parseInt(commands.get(i).substring(3,commands.get(i).length()))); } if (commands.get(i).equals("DF")) { deque.deleteFront(); } if (commands.get(i).equals("DR")) { deque.deleteRear(); } }
  • 5. fileReader.close(); } catch (Exception e) { // Deque methods are secure, so any exception thrown will be from input. System.out.println("Sorry, your input was invalid. Try running again with different input."); e.printStackTrace(); input.close(); return; } input.close(); } } Deque.java public class Deque { private DequeNode elts; // The pointer to the first element in the deque public void deque( ) { // Set elts member to null for empty deque elts = null; } public void insertFront( int item ) { // Insert the given item (as a node) into the first position of the Deque. DequeNode node = new DequeNode(item); if (this.isempty()) // Test for empty deque elts = node; else { DequeNode temp = elts; elts = node; elts.setNext(temp); if (temp.getPrev() == null) { // Test for deque with one item elts.setPrev(temp); temp.setNext(elts); } else { elts.setPrev(temp.getPrev()); temp.getPrev().setNext(elts);
  • 6. } temp.setPrev(elts); } } public void insertRear( int item ) { // Insert the given item (as a node) into the last position of the Deque. DequeNode node = new DequeNode(item); if (this.isempty()) // Test for empty deque elts = node; else { node.setNext(elts); if (elts.getPrev() == null) { // Test for deque with one item node.setPrev(elts); elts.setNext(node); } else { DequeNode temp = elts.getPrev(); node.setPrev(temp); temp.setNext(node); } elts.setPrev(node); } } public int deleteFront( ) { // Delete and return the element stored in the first node of the Deque. if (!this.isempty()) { int val = elts.getVal(); if (elts.getPrev() == null) // If there's only 1 item, just delete it. elts = null; else { elts.getPrev().setNext(elts.getNext()); elts.getNext().setPrev(elts.getPrev()); elts = elts.getNext(); } return val; }
  • 7. else { System.out.println("Deque is empty! Returning 0..."); return 0; } } public int deleteRear( ) { // Delete and return the element stored in the last node of the Deque. if (!this.isempty()) { int val; if (elts.getPrev() == null) { // If there's only 1 item, just delete it. val = elts.getVal(); elts = null; return val; } else { val = elts.getPrev().getVal(); DequeNode oldRear = elts.getPrev(); oldRear.getPrev().setNext(elts); elts.setPrev(oldRear.getPrev()); return val; } } else { System.out.println("Deque is empty! Returning 0..."); return 0; } } public boolean isempty( ) { // Returns true if the Deque is currently empty or false if it is not. return (elts == null); } public void printDeque( ) { // Print the integers from the list, one per line, from the first element through to the last in order. if (this.isempty())
  • 8. System.out.println("EMPTY DEQUE"); else { DequeNode index = elts; System.out.println(elts.getVal()); if (index.getNext() != null) { index = index.getNext(); while (index != elts) { System.out.println(index.getVal()); index = index.getNext(); } } } } } DequeNode.java package program1; public class DequeNode { protected DequeNode next; // Next pointer to next node protected DequeNode prev; // Previous pointer to previous node protected int val; // The integer value stored within the dequeNode. public DequeNode() { } public DequeNode(int val) { this.val = val; } public DequeNode getNext( ) { // Return the next field of the current dequeNode. return next; } public DequeNode getPrev( ) { // Return the prev field of the current dequeNode. return prev; } public void setNext( DequeNode n ) { // Set the next field of the current dequeNode to n. next = n; } public void setPrev( DequeNode p ) { // Set the prev field of the current dequenode to p.
  • 9. prev = p; } public int getVal( ) { // Simply returns the integer value stored in the val field. return val; } }