数据结构与算法之Stack(栈)——in dart

时间:2022-03-21 17:51:10

用dart 语言实现一个简单的stack(栈)。栈的内部用List实现。

 1 class Stack<E> {
 2   final List<E> _stack;
 3   final int capacity;
 4   int _top;
 5 
 6   Stack(this.capacity)
 7       : _top = -1,
 8         _stack = List<E>(capacity);
 9 
10   bool get isEmpty => _top == -1;
11   bool get isFull => _top == capacity - 1;
12   int get size => _top + 1;
13 
14   void push(E e) {
15     if (isFull) throw *Exception;
16     _stack[++_top] = e;
17   }
18 
19   E pop() {
20     if (isEmpty) throw StackEmptyException;
21     return _stack[_top--];
22   }
23 
24   E get top {
25     if (isEmpty) throw StackEmptyException;
26     return _stack[_top];
27   }
28 }
29 
30 class *Exception implements Exception {
31   const *Exception();
32   String toString() => '*Exception';
33 }
34 
35 class StackEmptyException implements Exception {
36   const StackEmptyException();
37   String toString() => 'StackEmptyException';
38 }
39 
40 void main() {
41   var stack = Stack<int>(10);
42   for (var i = 0; i < stack.capacity; i++) stack.push(i * i);
43   print(stack.top);
44 
45   var sbuff = StringBuffer();
46   while (!stack.isEmpty) sbuff.write('${stack.pop()} ');
47   print(sbuff.toString());
48 }