-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLLImplementation.java
More file actions
77 lines (66 loc) · 1.75 KB
/
LLImplementation.java
File metadata and controls
77 lines (66 loc) · 1.75 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
package Queue;
import java.util.EmptyStackException;
/**
* Linked List Implementation of Queue.
* Advantages -> Size is unlimited, Works like a LL.
*/
public class LLImplementation {
public static void main(String[] args) {
QueueLinkedList<String> queue = new QueueLinkedList<>();
queue.add("John");
queue.add("Seth");
queue.add("Becky Lynch");
System.out.println(queue.peek());
queue.remove();
queue.display();
}
public static class Node<T> {
T data;
Node<T> next;
Node(T data) {
this.data = data;
}
}
public static class QueueLinkedList<T> {
int size = 0;
private Node<T> head = null;
private Node<T> tail = null;
// Add Function
public void add(T x) {
Node<T> temp = new Node<>(x);
if (size == 0) {
head = tail = temp;
} else {
tail.next = temp;
tail = temp;
}
size++;
}
// Remove Function
public T remove() {
if (size == 0) {
throw new EmptyStackException();
}
T x = head.data;
head = head.next;
size--;
return x;
}
// Peek Function
public T peek() {
if (size == 0) {
throw new EmptyStackException();
}
return head.data;
}
// Function to Display
public void display() {
Node<T> temp = head;
while (temp != null) {
System.out.print(temp.data + ",");
temp = temp.next;
}
System.out.println();
}
}
}