数据结构与算法之Stack(栈)——in dart
Posted outerspace
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数据结构与算法之Stack(栈)——in dart相关的知识,希望对你有一定的参考价值。
用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的主要内容,如果未能解决你的问题,请参考以下文章