In: Computer Science
java code
public class LinkedQueue {
class DoubleLinkedNode {
public DoubleLinkedNode
next;
public DoubleLinkedNode prev;
public int element;
public DoubleLinkedNode(int
num){
next =
null;
prev =
null;
element =
num;
}
}
DoubleLinkedNode front, rear;
public String toString()
{
DoubleLinkedNode curr=front;
String s= "";
while(curr.next!=null)
{
s = s +
String.valueOf(curr.element)+" ";
curr=curr.next;
}
s = s + String.valueOf(curr.element);
return s;
}
public void remove(int count)
{
count--;
if(front==null)
new
Error("QueueUnderflowException");
if(count==0) {
front = front.next;
return ;
}
DoubleLinkedNode curr=front;
int i=0;
while(curr!=null && i!=count-1)
{
curr = curr.next;
i++;
}
if(i!=count-1)
new
Error("QueueUnderflowException");
if(curr.next.next==null)
rear=rear.prev;
curr.next = curr.next.next;
if(curr.next!=null)
curr.next.prev=curr;
}
public boolean swapStart() {
if(front==null || front.next==null)
return false;
DoubleLinkedNode curr=front;
front = front.next;
front.prev=null;
if(front.next!=null)
front.next.prev=curr;
curr.next=front.next;
curr.prev=front;
front.next=curr;
if(front.next.next==null)
rear = front.next;
return true;
}
public boolean swapEnds() {
if(front==null || front.next==null)
return false;
if(front.next.next==null)
return swapStart(); //when Queue
contain two element
rear.next=front.next;
rear.prev.next=front;
front.prev=rear.prev;
front.next.prev=rear;
front.next=null;
rear.prev=null;
DoubleLinkedNode curr;
curr=front;
front=rear;
rear=curr;
return true;
}
}