Write a method with signature "concatenate(LinkedQueue<E> Q2)" for the LinkedQueue<E> class that takes all elements of Q2 and appends them to the end of the original queue. The operation should run in O(1) time and should result in Q2 being an empty queue. Write the necessary code to test the method.You may just modify the SinglyLinkedList class to add necessary support.
LinkedQueue Class
public class LinkedQueue<E> implements Queue<E> {
/** The primary storage for elements of the queue */
private SinglyLinkedList<E> list = new
SinglyLinkedList<>(); // an empty list
/** Constructs an initially empty queue. */
public LinkedQueue() { } // new queue relies on the initially empty
list
@Override
public int size() { return list.size(); }
@Override
public boolean isEmpty() { return list.isEmpty(); }
@Override
public void enqueue(E element) { list.addLast(element); }
@Override
public E first() { return list.first(); }
@Override
public E dequeue() { return list.removeFirst(); }
public String toString() {
return list.toString();
}
}
Queue Class
public interface Queue<E> {
int size();
boolean isEmpty();
void enqueue(E e);
E first();
E dequeue();
}
SinglyLinkedList
public class SinglyLinkedList<E> implements Cloneable {
//---------------- nested Node class ----------------
private static class Node<E> {
/** The element stored at this node */
private E element; // reference to the element stored at this
node
/** A reference to the subsequent node in the list */
private Node<E> next; // reference to the subsequent node in
the list
public Node(E e, Node<E> n) {
element = e;
next = n;
}
// Accessor methods
public E getElement() { return element; }
public Node<E> getNext() { return next; }
// Modifier methods
public void setNext(Node<E> n) { next = n; }
} //----------- end of nested Node class -----------
// instance variables of the SinglyLinkedList
/** The head node of the list */
private Node<E> head = null; // head node of the list (or
null if empty)
/** The last node of the list */
private Node<E> tail = null; // last node of the list (or
null if empty)
/** Number of nodes in the list */
private int size = 0; // number of nodes in the list
/** Constructs an initially empty list. */
public SinglyLinkedList() { } // constructs an initially empty
list
public int size() { return size; }
public boolean isEmpty() { return size == 0; }
public E first() { // returns (but does not remove) the first
element
if (isEmpty()) return null;
return getHead().getElement();
}
public E last() { // returns (but does not remove) the last
element
if (isEmpty()) return null;
return tail.getElement();
}
public Node<E> getHead() {
return head;
}
public void setHead(Node<E> head) {
this.head = head;
}
// update methods
public void swapNodes(int posNode1, int
posNode2){
if(posNode1==posNode2)return;//Don't do anything if
they're the same
Node<E> prevNode1 = null;
Node<E> prevNode2 = null;
Node<E> currentNode = getHead();//reference to start
int position = 1;
//find previous nodes of nodes to be swapped
while( currentNode!= null && currentNode.getNext()!= null
)
{
if(position == posNode1 - 1){
prevNode1 = currentNode;//if current node is before the position of
node to be swapped, set it
}
else if(position == posNode2 - 1){
prevNode2 = currentNode;
}
if(null != prevNode1 && null != prevNode2){
break;
}
currentNode = currentNode.getNext();
position++;
}
Node<E> node1 = prevNode1.getNext();//nodes to swap
Node<E> node2 = prevNode2.getNext();
Node<E> aftNode1 = node1.getNext();//nodes in list
Node<E> aftNode2 = node2.getNext();
prevNode1.setNext(node2);//putting them in list
prevNode2.setNext(node1);
node2.setNext(aftNode1);//link to next
node1.setNext(aftNode2);
}
public void addFirst(E e) { // adds element e to the front of the
list
setHead(new Node<>(e, getHead())); // create and link a new
node
if (size == 0)
tail = getHead(); // special case: new node becomes tail also
size++;
}
public void addLast(E e) { // adds element e to the end of the
list
Node<E> newest = new Node<>(e, null); // node will
eventually be the tail
if (isEmpty())
setHead(newest); // special case: previously empty list
else
tail.setNext(newest); // new node after existing tail
tail = newest; // new node becomes the tail
size++;
}
public E removeFirst() { // removes and returns the first
element
if (isEmpty()) return null; // nothing to remove
E answer = getHead().getElement();
setHead(getHead().getNext()); // will become null if list had only
one node
size--;
if (size == 0)
tail = null; // special case as list is now empty
return answer;
}
@SuppressWarnings({})
public boolean equals(Object o) {
if (o == null) return false;
if (getClass() != o.getClass()) return false;
SinglyLinkedList<?> other = (SinglyLinkedList<?>) o; //
use nonparameterized type
if (size != other.size) return false;
Node<E> walkA = getHead(); // traverse the primary list
Node<?> walkB = other.getHead(); // traverse the secondary
list
while (walkA != null) {
if (!walkA.getElement().equals(walkB.getElement())) return false;
//mismatch
walkA = walkA.getNext();
walkB = walkB.getNext();
}
return true; // if we reach this, everything matched
successfully
}
@SuppressWarnings({"unchecked"})
public SinglyLinkedList<E> clone() throws
CloneNotSupportedException {
// always use inherited Object.clone() to create the initial
copy
SinglyLinkedList<E> other = (SinglyLinkedList<E>)
super.clone(); // safe cast
if (size > 0) { // we need independent chain of nodes
other.setHead(new Node<>(getHead().getElement(),
null));
Node<E> walk = getHead().getNext(); // walk through remainder
of original list
Node<E> otherTail = other.getHead(); // remember most
recently created node
while (walk != null) { // make a new node storing same
element
Node<E> newest = new Node<>(walk.getElement(),
null);
otherTail.setNext(newest); // link previous node to this one
otherTail = newest;
walk = walk.getNext();
}
}
return other;
}
public int hashCode() {
int h = 0;
for (Node<E> walk=getHead(); walk != null; walk =
walk.getNext()) {
h ^= walk.getElement().hashCode(); // bitwise exclusive-or with
element's code
h = (h << 5) | (h >>> 27); // 5-bit cyclic shift of
composite code
}
return h;
}
public String toString() {
StringBuilder sb = new StringBuilder("(");
Node<E> walk = getHead();
while (walk != null) {
sb.append(walk.getElement());
if (walk != tail)
sb.append(", ");
walk = walk.getNext();
}
sb.append(")");
return sb.toString();
}
//NEW
public static <E> SinglyLinkedList<E>
concatenate(SinglyLinkedList<E> L,
SinglyLinkedList<E>
M)
{
//tranverse the first list
//Create new node v
Node<E> v= new Node<E>(null, null);
v=L.head;//point to head
//scroll over L nodes
while (v.getNext()!=null)
v=v.getNext();
//where is the last node heldd?
//link headerof list M
v.setNext(M.head);
//return concat list
SinglyLinkedList<E> C=L;
return C;
}
//main method
public static void main(String[] args)
{
SinglyLinkedList<String> list1 = new
SinglyLinkedList<String>();
list1.addFirst("comp-254");
list1.addLast("comp-304");
list1.addLast("comp308");
SinglyLinkedList<String> list2 = new
SinglyLinkedList<String>();
list2.addFirst("comp-255");
list2.addLast("comp-307");
list2.addLast("comp306");
SinglyLinkedList<String>
list3=concatenate(list1, list2);
System.out.println(list3);
}
}
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
EDIT: getting character limit error while trying to submit the answer. So I'm pasting the answer as plain text, which may cause loss of formatting of the code. But the code will work as needed.
// LinkedQueue.java
public class LinkedQueue<E> implements Queue<E> {
/** The primary storage for elements of the queue
*/
private SinglyLinkedList<E> list = new
SinglyLinkedList<E>(); // an empty
// list
/** Constructs an initially empty queue. */
public LinkedQueue() {
} // new queue relies on the initially empty list
@Override
public int size() {
return list.size();
}
@Override
public boolean isEmpty() {
return list.isEmpty();
}
@Override
public void enqueue(E element) {
list.addLast(element);
}
@Override
public E first() {
return list.first();
}
@Override
public E dequeue() {
return list.removeFirst();
}
public String toString() {
return list.toString();
}
/**
* method to concatenate another LinkedQueue to this
queue. Made necessary
* changes to SinglyLinkedList class to run this method
in O(1) time.
*
* @param Q2
* linked queue to be concatenated. will be empty
after
* concatenation
*/
public void concatenate(LinkedQueue<E> Q2)
{
// checking if list on this queue
is empty
if (list.isEmpty()) {
// adjusting
head, tail and size to that of Q2
list.setHead(Q2.list.getHead());
list.setTail(Q2.list.getTail());
list.setSize(Q2.list.size());
// making Q2
empty
Q2.list.setHead(null);
Q2.list.setTail(null);
Q2.list.setSize(0);
} else {
// list not
empty, so we append the head node of Q2 to the tail of
// this
queue
list.getTail().setNext(Q2.list.getHead());
// setting this
queue's tail to Q2's tail
list.setTail(Q2.list.getTail());
// setting the
size as needed
list.setSize(list.size() + Q2.list.size());
// making Q2
empty
Q2.list.setHead(null);
Q2.list.setTail(null);
Q2.list.setSize(0);
}
}
}
// updated SinglyLinkedList.java file
public class SinglyLinkedList<E> implements Cloneable
{
// ---------------- nested Node class
----------------
//made Node class to public static.
public static class Node<E> {
/** The element stored at this
node */
private E element; // reference to
the element stored at this node
/** A reference to the
subsequent node in the list */
private Node<E> next; //
reference to the subsequent node in the list
public Node(E e, Node<E>
n) {
element =
e;
next = n;
}
// Accessor methods
public E getElement() {
return
element;
}
public Node<E> getNext()
{
return
next;
}
// Modifier methods
public void
setNext(Node<E> n) {
next = n;
}
} // ----------- end of nested Node class -----------
// instance variables of the SinglyLinkedList
/** The head node of the list */
private Node<E> head = null; // head node of the
list (or null if empty)
/** The last node of the list */
private Node<E> tail = null; // last node of the
list (or null if empty)
/** Number of nodes in the list */
private int size = 0; // number of nodes in the
list
/** Constructs an initially empty list. */
public SinglyLinkedList() {
} // constructs an initially empty list
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public E first() { // returns (but does not remove)
the first element
if (isEmpty())
return
null;
return
getHead().getElement();
}
public E last() { // returns (but does not remove)
the last element
if (isEmpty())
return
null;
return tail.getElement();
}
public Node<E> getHead() {
return head;
}
public void setHead(Node<E> head) {
this.head = head;
}
// update methods
public void swapNodes(int posNode1, int posNode2)
{
if (posNode1 == posNode2)
return;// Don't
do anything if they're the same
Node<E> prevNode1 =
null;
Node<E> prevNode2 =
null;
Node<E> currentNode =
getHead();// reference to start
int position = 1;
// find previous nodes of nodes
to be swapped
while (currentNode != null
&& currentNode.getNext() != null) {
if (position ==
posNode1 - 1) {
prevNode1 = currentNode;// if current node is
before the
// position of node to be swapped, set
// it
} else if
(position == posNode2 - 1) {
prevNode2 = currentNode;
}
if (null !=
prevNode1 && null != prevNode2) {
break;
}
currentNode =
currentNode.getNext();
position++;
}
Node<E> node1 =
prevNode1.getNext();// nodes to swap
Node<E> node2 =
prevNode2.getNext();
Node<E> aftNode1 =
node1.getNext();// nodes in list
Node<E> aftNode2 =
node2.getNext();
prevNode1.setNext(node2);// putting
them in list
prevNode2.setNext(node1);
node2.setNext(aftNode1);// link to
next
node1.setNext(aftNode2);
}
public void addFirst(E e) { // adds element e to
the front of the list
setHead(new Node<E>(e,
getHead())); // create and link a new node
if (size == 0)
tail =
getHead(); // special case: new node becomes tail also
size++;
}
public void addLast(E e) { // adds element e to the
end of the list
Node<E> newest = new
Node<E>(e, null); // node will eventually be the
//
tail
if (isEmpty())
setHead(newest);
// special case: previously empty list
else
tail.setNext(newest); // new node after existing tail
tail = newest; // new node becomes
the tail
size++;
}
public E removeFirst() { // removes and returns the
first element
if (isEmpty())
return null; //
nothing to remove
E answer =
getHead().getElement();
setHead(getHead().getNext()); //
will become null if list had only one
// node
size--;
if (size == 0)
tail = null; //
special case as list is now empty
return answer;
}
@SuppressWarnings({})
public boolean equals(Object o) {
if (o == null)
return
false;
if (getClass() !=
o.getClass())
return
false;
SinglyLinkedList<?> other =
(SinglyLinkedList<?>) o; // use
// nonparameterized
// type
if (size != other.size)
return
false;
Node<E> walkA = getHead(); //
traverse the primary list
Node<?> walkB =
other.getHead(); // traverse the secondary list
while (walkA != null) {
if
(!walkA.getElement().equals(walkB.getElement()))
return false; // mismatch
walkA =
walkA.getNext();
walkB =
walkB.getNext();
}
return true; // if we reach this,
everything matched successfully
}
@SuppressWarnings({ "unchecked" })
public SinglyLinkedList<E> clone() throws
CloneNotSupportedException {
// always use inherited
Object.clone() to create the initial copy
SinglyLinkedList<E> other =
(SinglyLinkedList<E>) super.clone(); // safe
// cast
if (size > 0) { // we need
independent chain of nodes
other.setHead(new Node<E>(getHead().getElement(),
null));
Node<E>
walk = getHead().getNext(); // walk through remainder of
//
original list
Node<E>
otherTail = other.getHead(); // remember most recently
// created node
while (walk !=
null) { // make a new node storing same element
Node<E> newest = new
Node<E>(walk.getElement(), null);
otherTail.setNext(newest); // link previous node
to this one
otherTail = newest;
walk = walk.getNext();
}
}
return other;
}
public int hashCode() {
int h = 0;
for (Node<E> walk =
getHead(); walk != null; walk = walk.getNext()) {
h ^=
walk.getElement().hashCode(); // bitwise exclusive-or with
//
element's code
h = (h <<
5) | (h >>> 27); // 5-bit cyclic shift of composite
code
}
return h;
}
public String toString() {
StringBuilder sb = new
StringBuilder("(");
Node<E> walk =
getHead();
while (walk != null) {
sb.append(walk.getElement());
if (walk !=
tail)
sb.append(", ");
walk =
walk.getNext();
}
sb.append(")");
return sb.toString();
}
// NEW
public static <E> SinglyLinkedList<E>
concatenate(SinglyLinkedList<E> L,
SinglyLinkedList<E> M) {
// tranverse the first list
// Create new node v
Node<E> v = new
Node<E>(null, null);
v = L.head;// point to head
// scroll over L nodes
while (v.getNext() != null)
v =
v.getNext();
// where is the last node
heldd?
// link headerof list M
v.setNext(M.head);
// return concat list
SinglyLinkedList<E> C =
L;
return C;
}
// extra methods needed for the concatenation
// returns the tail node
public Node<E> getTail() {
return tail;
}
// sets the tail node
public void setTail(Node<E> tail) {
this.tail = tail;
}
// sets the size to a new value (needed after
concatenation.)
public void setSize(int size) {
this.size = size;
}
// main method
public static void main(String[] args) {
SinglyLinkedList<String>
list1 = new SinglyLinkedList<String>();
list1.addFirst("comp-254");
list1.addLast("comp-304");
list1.addLast("comp308");
SinglyLinkedList<String>
list2 = new SinglyLinkedList<String>();
list2.addFirst("comp-255");
list2.addLast("comp-307");
list2.addLast("comp306");
SinglyLinkedList<String>
list3 = concatenate(list1, list2);
System.out.println(list3);
}
}
// Test.java for testing concatenate method
public class Test {
public static void main(String[] args) {
//creating two Queues and testing
concatenate method
LinkedQueue<Integer>
queue1=new LinkedQueue<Integer>();
queue1.enqueue(10);
queue1.enqueue(20);
queue1.enqueue(30);
queue1.enqueue(40);
queue1.enqueue(50);
LinkedQueue<Integer>
queue2=new LinkedQueue<Integer>();
queue2.enqueue(60);
queue2.enqueue(70);
queue2.enqueue(80);
queue2.enqueue(90);
queue2.enqueue(100);
System.out.println("Queue1:
"+queue1);
System.out.println("Queue2:
"+queue2);
System.out.println("Concatenating
Queue1 and Queue2");
queue1.concatenate(queue2);
System.out.println("Queue1:
"+queue1);
System.out.println("Queue2:
"+queue2);
System.out.println("Now
Concatenating Queue2 and Queue1");
queue2.concatenate(queue1);
System.out.println("Queue1:
"+queue1);
System.out.println("Queue2:
"+queue2);
}
}
/*OUTPUT*/
Queue1: (10, 20, 30, 40, 50)
Queue2: (60, 70, 80, 90, 100)
Concatenating Queue1 and Queue2
Queue1: (10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
Queue2: ()
Now Concatenating Queue2 and Queue1
Queue1: ()
Queue2: (10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
Write a method with signature "concatenate(LinkedQueue<E> Q2)" for the LinkedQueue<E> class that takes all elements of...
Question: SWAPPING NODES IN A SINGULARLY LINKED LIST: I am attempting to create a program that swaps 2 nodes (no matter where they are in the list) and am having some difficulty. I can't seem to figure out why this swap method is throwing an error. Code: (SWAPPING METHOD AND TEST LINE BOLDED) package linkedlists; public class SinglyLinkedList<E> implements Cloneable { //---------------- nested Node class ---------------- /** * Node of a singly linked list, which stores a reference to its...
Data Structures - Singly Linked Lists You will add a method swapNodes to SinglyLinkedList class (below). This method should swap two nodes node1 and node2 (and not just their contents) given references only to node1 and node2. The new method should check if node1 and node2 are the same node, etc. Write the main method to test the swapNodes method. You may need to traverse the list. package linkedlists; public class SinglyLinkedList<E> implements Cloneable { // ---------------- nested Node class...
Here is the IntegerLinkedList_incomplete
class:
public class IntegerLinkedList {
static class Node {
/** The element stored at this node */
private int element; // reference to the element stored at this node
/** A reference to the subsequent node in the list */
private Node next; // reference to the subsequent node in the list
/**
* Creates a node with the given element and next node.
*
* @param e the element to be stored
* @param n...
Write a Client class with a main method that tests the data structures as follows: For the ArrayStack, LinkedStack, ArrayQueue and LinkedQueue: Perform a timing test for each of these data structures. Each timing test should measure in nanoseconds how long it takes to add N Integers to the structure and how long it takes to remove N Integers from the structure. N should vary from 10 to 100,000,000 increasing N by a factor of 10 for each test. Depending...
Q1: You can find a file that defines the CircularlyLinked List class similar to what we discussed in the class. Download the file and work on it. Your task is to: 1. Complete the missing methods in the file as discussed in the class. Search for the comment/" MISSING / in the file to see the methods that need to be completed. 2. Add the following methods to the class a. public Node getMin 1. Task: find the node with...
solve this Q in java languege Write a method that return DoublyLinkedList as reversed string For example: If the elements of a list is 1, 2, 3, 4, 5, 6 the reverse string should be 6, 5, 4, 3, 2, 1 implement reverse method you have two steps: 1- you should start traversing from the last element of DoublyLinkedList (the previous of the trailer) 2- you should add the element inside each node to string don't forget the space in...
Java help: Please help complete the locate method that is in bold.. public class LinkedDoubleEndedList implements DoubleEndedList { private Node front; // first node in list private Node rear; // last node in list private int size; // number of elements in list ////////////////////////////////////////////////// // YOU MUST IMPLEMENT THE LOCATE METHOD BELOW // ////////////////////////////////////////////////// /** * Returns the position of the node containing the given value, where * the front node is at position zero and the rear node is...
In Java Language. Modify the LinkedPostionalList class to support a method swap(p,q) that causes the underlying nodes referenced by positions p and q to be exchanged for each other. Relink the existing nodes, do not create any new nodes. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- package lists; import java.util.Iterator; import java.util.NoSuchElementException; public class LinkedPositionalList implements PositionalList { //---------------- nested Node class ---------------- /** * Node of a doubly linked list, which stores a reference to its * element and to both the previous and next...
can someone please fix this error in the stack file at line 18 ( class Stack2:public Stack { ) this is thew error ----> expected class name before '{' token Queue.h --> #include "Stack.hpp" template <typename ITEM> class Queue { private: ITEM item; Stack <ITEM> * s1= new Stack<ITEM>; Stack <ITEM> * s2= new Stack<ITEM>; public: Queue(){}; bool enqueue (ITEM item); bool dequeue (ITEM &item); bool check = true; ~Queue(); }; //this is the class which contains the functions of...
C++: I need implement this code using Double Linked List using the cosiderations 1. head point to null in an empty list 2. There is not need of a tail pointer /*This class implements the singly linked list using templates Each list has two attributes: -head: first node in the list -tail: last node in the list #include "circDLLNode.h" template class { public: //Default constructor: creates an empty list (); //Destructor: deallocate memory ~(); ...