美文网首页
数据结构与算法之Stack(栈)——in dart

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

作者: compute | 来源:发表于2019-01-11 18:21 被阅读0次

用dart 语言实现一个简单的stack(栈)。代码如下:

class Stack<E> {
  final List<E> _stack;
  final int capacity;
  int _top;

  Stack(this.capacity)
      : _top = -1,
        _stack = List<E>(capacity);

  bool get isEmpty => _top == -1;
  bool get isFull => _top == capacity - 1;
  int get size => _top + 1;

  void push(E e) {
    if (isFull) throw StackOverFlowException;
    _stack[++_top] = e;
  }

  E pop() {
    if (isEmpty) throw StackEmptyException;
    return _stack[_top--];
  }

  E get top {
    if (isEmpty) throw StackEmptyException;
    return _stack[_top];
  }
}

class StackOverFlowException implements Exception {
  const StackOverFlowException();
  String toString() => 'StackOverFlowException';
}

class StackEmptyException implements Exception {
  const StackEmptyException();
  String toString() => 'StackEmptyException';
}

void main() {
  var stack = Stack<int>(10);
  for (var i = 0; i < stack.capacity; i++) stack.push(i * i);
  print(stack.top);

  var sbuff = StringBuffer();
  while (!stack.isEmpty) sbuff.write('${stack.pop()} ');
  print(sbuff.toString());
}

相关文章

网友评论

      本文标题:数据结构与算法之Stack(栈)——in dart

      本文链接:https://www.haomeiwen.com/subject/wiffdqtx.html