1. 程式人生 > >數據結構與算法之Stack(棧)——in dart

數據結構與算法之Stack(棧)——in dart

span on() art pre 一個 code overflow 數據結構 tostring

用dart 語言實現一個簡單的stack(棧)。

 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 }

數據結構與算法之Stack(棧)——in dart