Created
August 27, 2022 12:15
-
-
Save z1nc0r3/6a825a0f0e5b9e3f5557a5346760fef4 to your computer and use it in GitHub Desktop.
Queue using Linked List
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
class Node { | |
Node next; | |
int value; | |
Node (int value) { | |
this.value = value; | |
} | |
} | |
public class LinkedQueue { | |
private Node front = null; | |
private Node rear = null; | |
public void enQueue(int value) { | |
Node newNode = new Node(value); | |
if (isEmpty()) { | |
front = rear = newNode; | |
} else { | |
rear.next = newNode; | |
rear = newNode; | |
} | |
} | |
public void deQueue() { | |
if (isEmpty()) { | |
System.out.println("Queue is empty."); | |
return; | |
} else { | |
front = front.next; | |
if (front == null) | |
rear = null; | |
} | |
} | |
public void peek() { | |
if (isEmpty()) { | |
System.out.println("Queue is empty."); | |
return; | |
} else { | |
System.out.println(front.value); | |
} | |
} | |
public void print() { | |
System.out.println(); | |
Node temp = front; | |
while (temp != null) { | |
System.out.println(temp.value); | |
temp = temp.next; | |
} | |
System.out.println(); | |
} | |
public boolean isEmpty() { | |
return (front == null); | |
} | |
public static void main(String[] args) { | |
Scanner read = new Scanner(System.in); | |
LinkedQueue myQ = new LinkedQueue(); | |
myQ.deQueue(); | |
for (int i=0; i<5; i++) { | |
myQ.enQueue(read.nextInt()); | |
} | |
myQ.peek(); | |
myQ.print(); | |
myQ.deQueue(); | |
myQ.print(); | |
for (int i=0; i<5; i++) { | |
myQ.deQueue(); | |
} | |
myQ.enQueue(1); | |
myQ.enQueue(2); | |
myQ.print(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment