-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNaughtyLLQueue.java
More file actions
99 lines (77 loc) · 4.71 KB
/
Copy pathNaughtyLLQueue.java
File metadata and controls
99 lines (77 loc) · 4.71 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
91
92
93
94
95
96
97
98
99
public class NaughtyLLQueue<E> implements Queue<E>{
// Maintains the head and tail nodes of the list
private Node<E> head, tail;
// check if stack is empty. if head == null, there are no nodes
public boolean isEmpty() {
return head == null;
}
// (This just adds a new node to the front of the queue with a special
// case for adding to an empty list since that requires altering the head.)
public void enqueue(E newValue) {
// Create a new node containing the newValue and whose
// next points to null
Node<E> newNode = new Node<>(newValue, null);
// Adding to the "front" of a non-empty list
if (!isEmpty()) {
newNode.setNext(head); // have newNode next point to next of node after Head
head = tail = newNode;
}
else
head = tail = newNode;
}
// Removes and returns the element from the back of the stack , a NullPointerException
public E dequeue() {
if (!isEmpty()) {
int count = 1;
Node<E> current = head;
while(current.getNext() != null){
current = current.getNext();
count++;
}
E dataToReturn = current.getData();
Node<E> removeNode = head;
if (count == 1) {
head = tail = null;
dataToReturn = removeNode.getData();
}
else {
for (int i = 1; i < count - 1; i++) {
removeNode = removeNode.getNext();
}
removeNode.setNext(null);
tail = removeNode;
}
if (head == null)
tail = null;
return dataToReturn;
}
else
return null; // This indicates that the queue is empty, or head = null
}
// Returns (but does not remove) the head of the queue
public E peek() {
if (!isEmpty())
return head.getData();
else
return null; // This indicates that the queue is empty
}
public String toString() {
String result = "LLQueue object, elements (front to back):\n";
for (Node<E> temp = head; temp != null; temp = temp.getNext())
result += temp.getData() + "\n";
return result;
}
public static void main(String[] args) {
Queue<String> test = new NaughtyLLQueue<>();
System.out.println(test);
for (int i = 0; i < 8; i++) {
test.enqueue(i + "");
}
System.out.println(test);
System.out.println("Returned and removed: " + test.dequeue());
System.out.println(test);
System.out.println("Returned and removed: " + test.dequeue());
System.out.println(test);
System.out.println("Peek : " + test.peek());
}
}