1
1
import 'Queue.dart' ;
2
2
3
- class LoopQueue <T > implements Queue <T >{
4
-
3
+ class LoopQueue <T > implements Queue <T > {
5
4
List ? arr;
6
- int front = 0 ,tail= 0 ;
7
- int size = 0 ;
5
+ int front = 0 , tail = 0 ;
6
+ int size = 0 ;
8
7
9
- LoopQueue (){
8
+ LoopQueue () {
10
9
arr = List .filled (10 , false );
11
10
}
12
11
13
- LoopQueue .capcity (int capacity){
14
- arr = List .filled (capacity+ 1 , false );
15
- }
12
+ // LoopQueue.capcity(int capacity){
13
+ // arr = List.filled(capacity+1, false);
14
+ // }
16
15
17
- int getCapacity (){
16
+ int getCapacity () {
18
17
//目前这种方式浪费一个空间
19
- int capacity = arr! .length- 1 ;
18
+ int capacity = arr! .length - 1 ;
20
19
return capacity;
21
20
}
22
21
23
22
@override
24
23
dequeue () {
25
- if (isEmpty ()){
24
+ if (isEmpty ()) {
26
25
throw Exception ("Cannot dequeue from an empty queue" );
27
26
}
28
27
T ret = arr! [front];
29
28
arr! [front] = null ;
30
29
front = (front + 1 ) % arr! .length;
31
30
size-- ;
32
- if (size == getCapacity () / 4 && getCapacity () / 2 != 0 ){
33
- resize ((getCapacity ()/ 2 ) as int );
31
+ if (size == getCapacity () / 4 && getCapacity () / 2 != 0 ) {
32
+ resize ((getCapacity () / 2 ) as int );
34
33
}
35
34
return ret;
36
35
}
37
36
38
- void resize (int newCapacity){
39
-
40
- List ? newArr = List .filled (newCapacity+ 1 , false );
41
- for (int i = 0 ; i < arr! .length ; i ++ ){
37
+ void resize (int newCapacity) {
38
+ List ? newArr = List .filled (newCapacity + 1 , false );
39
+ for (int i = 0 ; i < arr! .length; i++ ) {
42
40
newArr[i] = arr! [(i + front) % arr! .length];
43
41
}
44
42
arr = newArr;
@@ -48,17 +46,15 @@ class LoopQueue<T> implements Queue<T>{
48
46
49
47
@override
50
48
void enqueue (e) {
51
-
52
- if ((tail + 1 ) % arr! .length == front)
53
- resize (getCapacity () * 2 );
49
+ if ((tail + 1 ) % arr! .length == front) resize (getCapacity () * 2 );
54
50
arr! [tail] = e;
55
51
tail = (tail + 1 ) % arr! .length;
56
52
size++ ;
57
53
}
58
54
59
55
@override
60
56
getFront () {
61
- if (isEmpty ()){
57
+ if (isEmpty ()) {
62
58
throw Exception ("Queue is empty." );
63
59
}
64
60
return arr! [front];
@@ -71,21 +67,19 @@ class LoopQueue<T> implements Queue<T>{
71
67
72
68
@override
73
69
bool isEmpty () {
74
- return front == tail ;
70
+ return front == tail;
75
71
}
76
72
77
73
@override
78
74
String toString () {
79
75
StringBuffer buffer = new StringBuffer ();
80
76
buffer.write ("Queue: size = $size , capacity = ${getCapacity ()} \n " );
81
77
buffer.write ('front [' );
82
- for (int i = front ; i != tail ; i = (i + 1 ) % arr! .length){
78
+ for (int i = front; i != tail; i = (i + 1 ) % arr! .length) {
83
79
buffer.write (arr! [i]);
84
- if ((i + 1 ) % arr! .length != tail)
85
- buffer.write (", " );
80
+ if ((i + 1 ) % arr! .length != tail) buffer.write (", " );
86
81
}
87
82
buffer.write ("] tail" );
88
83
return buffer.toString ();
89
84
}
90
-
91
- }
85
+ }
0 commit comments