-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueue.java
More file actions
92 lines (78 loc) · 1.58 KB
/
Queue.java
File metadata and controls
92 lines (78 loc) · 1.58 KB
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
91
92
package a;
import java.util.*;
public class Queue<Item> implements Iterable<Item>{
private Node first;
private Node last;
private int N;
private class Node{
Item item;
Node next;
}
//队列是否为空
public boolean isEmpty(){
return first==null;
}
//队列长度
public int size(){
return N;
}
//进队列
public void enqueue(Item item){
Node newNode=new Node();
newNode.item=item;
//为空就头节点和尾节点都指向newNode
if(isEmpty()){
first=newNode;
last=newNode;
}
else{
last.next=newNode;
last=newNode;
}
N++;
}
//从头部出队列
public Item dequeue(){
if(isEmpty()){
throw new NoSuchElementException("队列为空!");
}
Item item=first.item;
first=first.next;
if(isEmpty()){
last=null;
}
N--;
return item;
}
//查看第一个元素
public Item peek() {
if (isEmpty()) throw new NoSuchElementException("队列为空!");
return first.item;
}
public String toString() {
StringBuilder s = new StringBuilder();
for (Item item : this)
s.append(item + " ");
return s.toString();
}
@Override
public Iterator<Item> iterator() {
return new ListIterator(first);
}
private class ListIterator implements Iterator<Item>{
private Node current;
public ListIterator(Node first){
this.current=first;
}
@Override
public boolean hasNext() {
return current!=null;
}
@Override
public Item next() {
Item item=current.item;
current=current.next;
return item;
}
}
}