数据结构与算法之Stack(栈)——重新实现

      之前发过一篇stack的实现,是采用dart内置的List类并固定长度数组实现的。这里重新实现一版,重复利用List类内置特性和方法。实现更为简洁。

 1 class Stack<E> {
 2   final List<E> _stack;
 3 
 4   Stack() : _stack = <E>[];
 5 
 6   bool get isEmpty => _stack.isEmpty;
 7   bool get isNotEmpty => _stack.isNotEmpty;
 8   int get size => _stack.length;
 9 
10   Iterable<E> get content => _stack.reversed;
11 
12   void push(E e) => _stack.add(e);
13 
14   E pop() {
15     if (_stack.isEmpty) throw StackEmptyException;
16     return _stack.removeLast();
17   }
18 
19   E get top {
20     if (_stack.isEmpty) throw StackEmptyException;
21     return _stack.last;
22   }
23 }
24 
25 class StackEmptyException implements Exception {
26   const StackEmptyException();
27   String toString() => 'StackEmptyException';
28 }

 

posted on 2019-01-15 16:57  Burkut  阅读(734)  评论(0编辑  收藏  举报