forked from iMeiji/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
QueueBasedOnSingleLinkedlist.java
59 lines (50 loc) · 1.35 KB
/
QueueBasedOnSingleLinkedlist.java
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
package struct.queue;
/**
* 基于单链表实现的队列
*/
public class QueueBasedOnSingleLinkedlist<T> {
// 队列的队首和队尾
private Node<T> head;
private Node<T> tail;
public void enqueue(T data) {
Node<T> newNode = new Node<>(data, null);
if (tail == null) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
tail = tail.next;
}
}
public T dequeue() {
if (head == null) {
return null;
}
T value = head.data;
head = head.next;
if (head == null) {
tail = null;
}
return value;
}
public static void main(String[] args) {
QueueBasedOnSingleLinkedlist<Integer> queue = new QueueBasedOnSingleLinkedlist<>();
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
System.out.println(queue.dequeue());
System.out.println(queue.dequeue());
System.out.println(queue.dequeue());
System.out.println(queue.dequeue());
queue.enqueue(4);
System.out.println(queue.dequeue());
}
public static class Node<T> {
private T data;
private Node next;
public Node(T data, Node next) {
this.data = data;
this.next = next;
}
}
}