-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathLinkedQueue.java
More file actions
83 lines (74 loc) · 2.12 KB
/
LinkedQueue.java
File metadata and controls
83 lines (74 loc) · 2.12 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
import java.util.NoSuchElementException;
public class LinkedQueue {
static class Node {
Object data;
Node next;
Node prev;
Node() {
this.data = null;
this.next = null;
this.prev = null;
}
Node(Object data) {
this.data = data;
this.prev = null;
this.next = null;
}
Node(Object data, Node next, Node prev) {
this.data = data;
this.next = next;
this.prev = prev;
}
}
Node main;
int length;
LinkedQueue() {
main = null;
length = 0;
}
public void insert(Object object) { // O(1)
Node objNode = new Node(object);
if(this.main == null) {
this.main = new Node(null, objNode, null);
} else {
if(this.main.prev == null) {
this.main.next.next = objNode;
objNode.prev = this.main.next;
} else {
this.main.prev.next = objNode;
objNode.prev = this.main.prev;
}
this.main.prev = objNode;
}
length++;
}
public Object remove() { // O(1)
if(this.main.next == null) throw new NoSuchElementException();
Node temp = this.main.next;
this.main.next = this.main.next.next;
length--;
return temp.data;
}
public Object check() { // O(1)
if(this.main.next == null) throw new NoSuchElementException();
return this.main.next.data;
}
public LinkedQueue reverse() {
LinkedQueue queue = new LinkedQueue();
for(Node a = main.prev; a != null; a = a.prev) {
queue.insert(a.data);
}
return queue;
}
@Override
public String toString() {
StringBuilder a = new StringBuilder("[ ");
for(Node i = main.next; i != null; i = i.next) {
a.append(i.data).append(" ");
}
return a + " ]";
}
public int size() { // O(1)
return length;
}
}