Line data Source code
1 : // Copyright 2026 The Authors. See the AUTHORS file for details.
2 : //
3 : // Licensed under the Apache License, Version 2.0 (the "License");
4 : // you may not use this file except in compliance with the License.
5 : // You may obtain a copy of the License at
6 : //
7 : // https://www.apache.org/licenses/LICENSE-2.0
8 : //
9 : // Unless required by applicable law or agreed to in writing, software
10 : // distributed under the License is distributed on an "AS IS" BASIS,
11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 : // See the License for the specific language governing permissions and
13 : // limitations under the License.
14 :
15 : import 'package:collection/collection.dart';
16 :
17 : /// A stack data structure.
18 : class Stack<E> {
19 : final List<E> _list = [];
20 :
21 6 : List<E> toList() => List.from(_list);
22 :
23 : /// Returns the number of elements in the stack.
24 3 : int get length => _list.length;
25 :
26 : /// Returns true if the stack is empty.
27 3 : bool get isEmpty => _list.isEmpty;
28 :
29 : /// Returns true if the stack is not empty.
30 3 : bool get isNotEmpty => _list.isNotEmpty;
31 :
32 : /// Pushes an element onto the top of the stack.
33 6 : void push(E item) => _list.add(item);
34 :
35 : /// Pushes all elements of [other] to the stack.
36 4 : void pushAll(Stack<E> other) => _list.addAll(other._list);
37 :
38 : /// Removes the top element and returns it.
39 6 : E pop() => _list.removeLast();
40 :
41 : /// Returns the top element, without removing it.
42 3 : E peek() => _list.last;
43 :
44 : /// Returns the top element, without removing it.
45 2 : E get top => peek();
46 :
47 : /// Calculate how far back in the stack a matching element is.
48 : ///
49 : /// Returns null if not found.
50 1 : int? distanceToElementWhere(bool Function(E element) test) {
51 2 : final pos = _list.lastIndexWhere(test);
52 2 : if (pos == -1) {
53 : return null;
54 : }
55 4 : final distance = _list.length - pos - 1;
56 : return distance;
57 : }
58 :
59 1 : @override
60 : bool operator ==(Object other) =>
61 : identical(this, other) ||
62 1 : other is Stack<E> &&
63 3 : runtimeType == other.runtimeType &&
64 4 : ListEquality().equals(_list, other._list);
65 :
66 1 : @override
67 2 : int get hashCode => Object.hashAll(_list);
68 : }
|