-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueue githib.java
More file actions
80 lines (60 loc) · 1.59 KB
/
Queue githib.java
File metadata and controls
80 lines (60 loc) · 1.59 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
// Queue implementation of Java.
import java.util.NoSuchElementException;
public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
MyQueue<Integer> q = new MyQueue<>();
System.out.println(q.isEmpty());
q.add(5);
q.add(3);
q.add(7);
//System.out.println(q.peek());
//System.out.println(q.isEmpty());
q.print_queue();
}
public static class MyQueue<T> {
private static class QueueNode<T> {
private T data;
private QueueNode<T> next;
public QueueNode(T data) {
this.data = data;
}
}
private QueueNode<T> first;
private QueueNode<T> last;
public void add(T item) {
QueueNode<T> t = new QueueNode<T>(item);
if (last != null) {
last.next = t;
}
last = t;
if (first == null) {
first = last;
}
}
public T remove() {
if (first == null) throw new NoSuchElementException();
T data = first.data;
first = first.next;
if (first == null) {
last = null;
}
return data;
}
public T peek() {
if (first == null) throw new NoSuchElementException();
return first.data;
}
public boolean isEmpty() {
return first == null;
}
public void print_queue(){
QueueNode pointer_print = first;
System.out.print(pointer_print.data+ ", ");
while (pointer_print.next != null){
pointer_print = pointer_print.next;
System.out.print(pointer_print.data+ ", ");
}
}
}
}