SlideShare a Scribd company logo
1 of 9
Download to read offline
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

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 .pdfsiennatimbok52331
 
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.pdfrozakashif85
 
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).pptxAbhishek 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).pptxGauravPandey43518
 
01-intro_stacks.ppt
01-intro_stacks.ppt01-intro_stacks.ppt
01-intro_stacks.pptsoniya555961
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой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 organizationecomputernotes
 
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).docxcarold11
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbRAtna29
 
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 ProgrammingMandeep Singh
 
Stack linked list
Stack linked listStack linked list
Stack linked listbhargav0077
 
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.pdfjyothimuppasani1
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data StructureZidny Nafan
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data StructureSriram Raj
 

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

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

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

Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 

Recently uploaded (20)

Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 

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; } }