Using Java, modify the LinkedQueue class to include a method that will remove th
ID: 3595141 • Letter: U
Question
Using Java, modify the LinkedQueue class to include a method that will remove the middle element in the queue (if there are an event number of elements, round down for the middle).
public class LinkedQueue {
LinkedNode front;
LinkedNode rear;
int count;
LinkedQueue() {
front = rear = null;
count = 0;
}
void enqueue(int x) {
LinkedNode newNode = new LinkedNode(x);
if (rear!=null)
rear.next = newNode;
else
front = newNode;
rear = newNode;
count++;
}
int dequeue() {
if (front==null) {
return -1;
}
if (front!=rear) {
int x = front.x;
front = front.next;
count--;
return x;
} else {
int x = front.x;
front = null;
rear = null;
count --;
return x;
}
}
int first() {
return front.x;
}
boolean isEmpty() {
return count==0;
}
int size() {
return count;
}
}
Explanation / Answer
public class LinkedQueue {
LinkedNode front;
LinkedNode rear;
int count;
LinkedQueue() {
front = rear = null;
count = 0;
}
void enqueue(int x) {
LinkedNode newNode = new LinkedNode(x);
if (rear!=null)
rear.next = newNode;
else
front = newNode;
rear = newNode;
count++;
}
void removeMiddleElement(){
int index = 1, toBeDeleted = 0;
if(front == null) // If Queue is empty
return -1;
if (count % 2 == 0) // If even
toBeDeleted = count / 2;
else
toBeDeleted = count / 2 + 1;
LinkedNode ptr = front, ptr1;
while(index < toBeDeleted){
ptr1 = ptr;
ptr = ptr.next;
index++;
}
// ptr holds to be deleted node
// while ptr1 holds it's previous one
ptr1.next = ptr.next;
ptr.next = null;
return ptr.x;
}
int dequeue() {
if (front==null) {
return -1;
}
if (front!=rear) {
int x = front.x;
front = front.next;
count--;
return x;
} else {
int x = front.x;
front = null;
rear = null;
count --;
return x;
}
}
int first() {
return front.x;
}
boolean isEmpty() {
return count==0;
}
int size() {
return count;
}
}
Cannot run the code to show output screenshots without a proper definition of LinkedNode which is not given in the question but the function to delete middle element should work fine with you. If you want output screenshots then please give the details of LinkedNode.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.