数据结构与算法之Stack(栈)——in dart
用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 StackOverFlowException; 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 StackOverFlowException implements Exception { 31 const StackOverFlowException(); 32 String toString() => 'StackOverFlowException'; 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 }