0% found this document useful (0 votes)
4 views3 pages

Java Queue Implementation Example

Uploaded by

Feben Getachew
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views3 pages

Java Queue Implementation Example

Uploaded by

Feben Getachew
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

// THIS GOES IN YOUR MAIN CLASS TO TEST YOUR CODE:

// -----------------------------------------------

package [Link];

public class Main {

public static void main(String[] args) {

Queue myQueue = new Queue(2);


[Link](1);

// (2) Items - Returns 2 Node


[Link]([Link]().value);
// (1) Item - Returns 1 Node
[Link]([Link]().value);
// (0) Items - Returns null
[Link]([Link]());

/*
EXPECTED OUTPUT:
----------------
2
1
null

*/

// THIS CODE GOES IN YOUR QUEUE CLASS:


// -----------------------------------

package [Link];

public class Queue {

private Node first;


private Node last;
private int length;

class Node {
int value;
Node next;

Node(int value) {
[Link] = value;
}
}

public Queue(int value) {


Node newNode = new Node(value);
first = newNode;
last = newNode;
length = 1;
}

public void printQueue() {


Node temp = first;
while (temp != null) {
[Link]([Link]);
temp = [Link];
}
}

public void getFirst() {


if (first == null) {
[Link]("First: null");
} else {
[Link]("First: " + [Link]);
}
}

public void getLast() {


if (last == null) {
[Link]("Last: null");
} else {
[Link]("Last: " + [Link]);
}
}

public void getLength() {


[Link]("Length: " + length);
}

public void enqueue(int value) {


Node newNode = new Node(value);
if (length == 0) {
first = newNode;
last = newNode;
} else {
[Link] = newNode;
last = newNode;
}
length++;
}

public Node dequeue() {


if(length == 0) return null;
Node temp = first;
if(length == 1) {
first = null;
last = null;
} else {
first = [Link];
[Link] = null;
}
length--;
return temp;
}
}

You might also like