Sunday, September 18, 2022

Implementing queue

 package LinearDSA;


/**

 * @author lokman 17/09/2022

 *

 */

public class Queue {

private ListNode front;

private ListNode rear;

private int length = 0;

public Queue() {

this.front = null;

this.rear = null;

}

private class ListNode {

private int data;

private ListNode next;

public ListNode(int data) {

this.data = data;

this.next = null;

}

}

public int length() {

return length;

}

public boolean isEmpty() {

return length == 0;

}

public void enqueue(int data) {

ListNode temp = new ListNode(data);

if (isEmpty()) {

front = temp;

} else {

rear.next = temp;

}

rear = temp;

length++;

}

public int dequeue() {

if(isEmpty()) {

System.out.println("Queue is empty");

}

int data  = front.data;

front = front.next;

if(front == null) {

rear = null;

}

length--;

return data;

}

public void print() {

if (isEmpty()) {

return;

}

ListNode current = front;

while (current != null) {

System.out.print(current.data + "-->");

current = current.next;

}

System.out.println("null");

}

public static void main(String[] args) {

Queue queue = new Queue();

queue.enqueue(10);

queue.enqueue(20);

queue.enqueue(30);

queue.print();

queue.dequeue();

queue.print();

}

}


No comments:

Post a Comment

Fluent interface pattern

 public class UserConfigurationManager {     private String userName;     private String password;     private UserConfigurationManager() { ...