-
Notifications
You must be signed in to change notification settings - Fork 0
/
MyQueueList.java
90 lines (83 loc) · 2.03 KB
/
MyQueueList.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
78
79
80
81
82
83
84
85
86
87
88
89
90
public class MyQueueList<E> implements MyQueue<E>{
private class Node<E> {
Node<E> prev;
Node<E> next;
E value;
Node(Node<E> prev, Node<E> next, E value) {
this.prev = prev;
this.next = next;
this.value = value;
}
@Override
public String toString() {
return "Node{" +
"value=" + value +
'}';
}
}
@Override
public void add(Object value) {
Node<E> newNode = new Node<>(tail, null, (E) value);
if (tail == null && head == null) {
tail = newNode;
head = newNode;
} else if (size == 1) {
tail = newNode;
head.next = tail;
tail.prev = head;
} else {
Node<E> oldTail = tail;
oldTail.next = newNode;
tail = newNode;
}
++size;
}
@Override
public void clear() {
Node<E> cur = head;
while (cur != null) {
Node<E> tmpNext = cur.next;
cur.prev = null;
cur.value = null;
cur.next = null;
cur = tmpNext;
}
head = tail = null;
size = 0;
}
@Override
public int size() {
return size;
}
@Override
public Object peek() {
return head;
}
@Override
public Object poll() {
if (size == 1) {
Object returnObj = peek();
head = tail = null;
return returnObj;
}
Object returnObj = head;
head.next.prev = null;
Node<E> tmpHead =head;
head = head.next;
tmpHead.next=null;
tmpHead.prev=null;
--size;
return returnObj;
}
public void printQueue() {
Node<E> cur = head;
while (cur != null) {
System.out.print(cur.value + " ");
cur = cur.next;
}
System.out.println();
}
private Node<E> head;
private Node<E> tail;
private int size = 0;
}