-
Notifications
You must be signed in to change notification settings - Fork 62
/
LinkedQueue.java
77 lines (64 loc) · 1.42 KB
/
LinkedQueue.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package datastructure.queue;
/**
* @author roseduan[roseduan520@gmail.com]
* @time 2019/10/31 23:30
* @description 使用链表实现队列
*/
public class LinkedQueue<T> {
private ListNode<T> head;
private ListNode<T> tail;
private int size;
public LinkedQueue(T val) {
ListNode<T> node = new ListNode<>(val);
this.head = node;
this.tail = node;
this.size = 1;
}
private static class ListNode<T>{
T val;
ListNode<T> next;
ListNode(T val) {
this.val = val;
this.next = null;
}
}
/**
* 入队列
*/
public boolean add(T value) {
ListNode<T> node = new ListNode<>(value);
if (head == null) {
head = node;
}
else {
tail.next = node;
}
tail = node;
size++;
return true;
}
/**
* 出队列
*/
public T dequeue() {
if (head == null){
return null;
}
ListNode<T> result = head;
T val = result.val;
head = head.next;
result = null;
size--;
return val;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
ListNode<T> p = head;
while (p != null) {
sb.append(p.val).append(" ");
p = p.next;
}
return sb.toString();
}
}