-
Notifications
You must be signed in to change notification settings - Fork 0
/
MyQueueLinked.java
57 lines (47 loc) · 1.27 KB
/
MyQueueLinked.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
package my.exercises.shortjob;
public class MyQueueLinked {
private Node head;
public Node tail;
private int count;
public boolean isFull(){return false;}
public boolean isEmpty(){return count == 0;}
public boolean enqueue(Object item){
Node node = new Node(item);
if(isEmpty())
head = node;
else
tail.setNext(node);
tail= node;
count++;
return true;
}
public Object peek(){return !isEmpty() ? head.getItem() : null;}
public Object dequeue(){
Object item = peek();
if(item != null){
head = head.getNext();
count--;
}
return item;
}
public void clear(){
for(; !isEmpty(); dequeue());
}
public int size(){return count;}
public String toString(){
StringBuffer sb = new StringBuffer();
for(Node node = head; node!= null; node= node.getNext()){
sb.append(node.getItem());
}
return sb.toString();
}
public static void main(String... args){
MyQueueLinked q = new MyQueueLinked();
q.enqueue(1);
q.enqueue(2);
q.enqueue(5);
q.enqueue(7);
System.out.println(q.dequeue());
System.out.print(q);
}
}