-
Notifications
You must be signed in to change notification settings - Fork 0
/
GeneralizedQueue.java
55 lines (54 loc) · 951 Bytes
/
GeneralizedQueue.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
public class GeneralizedQueue<T>{
private int size;
private Node first, last;
private class Node{
Node next;
Node prev;
T item;
Node(T item){
this.item = item;
}
}
public int size(){
return size;
}
public boolean isEmpty(){
return size == 0;
}
public void insert(T item){
if(size == 0){
first = new Node(item);
last = first;
}
else{
last.next = new Node(item);
last.next.prev = last;
last = last.next;
}
size++;
}
public T delete(int k){
//if(k > size) return null;
Node curNode = last;
for(int i = 0; i < k && curNode.prev != null; ++i){
curNode = curNode.prev;
}
if(size == 1){
first = last = null;
}
else if(curNode == first){
first = first.next;
first.prev = null;
}
else if(curNode == last){
last = last.prev;
last.next = null;
}
else{
curNode.prev.next = curNode.next;
curNode.next.prev = curNode.prev;
}
size--;
return curNode.item;
}
}