-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueueUsingLinkedList.java
More file actions
90 lines (61 loc) · 1.72 KB
/
QueueUsingLinkedList.java
File metadata and controls
90 lines (61 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Dell
*/
import java.util.*;
import java.io.*;
import DS.*;
public class QueueUsingLinkedList {
public static Node head;
public static Node tail;
public static void enqueue(int data){
Node current = new Node();
if(head == null){
current.data = data;
current.next = head;
tail = current;
head = current;
}
else{
//we use a tail node to point the tail of the queue,once new node is added it will
// add the address of the new node to the current tail node's next
//hence we can always enqueue in O(1) as we do not have to use the while loop to
// traverse the list and add the new element at the last of the queue.
Node latest = new Node();
latest.data = data;
tail.next = latest;
latest.next = null;
tail = latest;
}
}
public static void print(){
Node temp = head;
while(temp != null){
System.out.print(temp.data+"->");
temp = temp.next;
}
}
public static int dequeue(){
Node temp = head;
head = temp.next;
return temp.data;
}
public static void main(String[] args){
head = null;
enqueue(5);
enqueue(15);
enqueue(25);
enqueue(35);
enqueue(45);
enqueue(55);
enqueue(65);
print();
System.out.println("\n"+dequeue());
print();
}
}