-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implemented singly linked list queue in java
- Loading branch information
Showing
1 changed file
with
63 additions
and
0 deletions.
There are no files selected for viewing
63 changes: 63 additions & 0 deletions
63
data_structures/04. Queues/java/SinglyLinkedListQueue.java
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
class Node{ | ||
int val; | ||
Node next; | ||
Node(int val){ | ||
this.val = val; | ||
this.next = null; | ||
} | ||
} | ||
|
||
public class SinglyLinkedListQueue { | ||
int length; | ||
Node head; | ||
Node tail; | ||
|
||
public SinglyLinkedListQueue(){ | ||
this.head = null; | ||
this.tail = null; | ||
this.length = 0; | ||
} | ||
|
||
private void enqueue(int val){ | ||
Node newNode = new Node(val); | ||
|
||
if(this.length == 0){ | ||
this.head = newNode; | ||
}else{ | ||
this.tail.next = newNode; | ||
|
||
} | ||
this.tail = newNode; | ||
this.length++; | ||
} | ||
|
||
private Integer dequeue(){ | ||
|
||
if(this.length == 0){ | ||
return null; | ||
} | ||
|
||
Node node = this.head; | ||
if(this.length == 1){ | ||
this.head = null; | ||
this.tail = null; | ||
}else{ | ||
this.head = this.head.next; | ||
} | ||
|
||
node.next = null; | ||
length--; | ||
return node.val; | ||
} | ||
|
||
public static void main(String[] args) { | ||
SinglyLinkedListQueue sllq = new SinglyLinkedListQueue(); | ||
sllq.enqueue(0); | ||
sllq.enqueue(2); | ||
sllq.enqueue(3); | ||
System.out.println(sllq.dequeue()); | ||
System.out.println(sllq.dequeue()); | ||
System.out.println(sllq.dequeue()); | ||
System.out.println(sllq.dequeue()); | ||
} | ||
} |