|
| 1 | +// Implementation of a generic LIFO (last-in, first-out) stack. |
| 2 | +// Reference: https://en.wikipedia.org/wiki/Stack_(abstract_data_type) |
| 3 | + |
| 4 | +// Stack is a generic last-in, first-out (LIFO) collection. |
| 5 | +struct Stack[T] { |
| 6 | + items: []T |
| 7 | +} |
| 8 | + |
| 9 | +impl Stack { |
| 10 | + // Push adds an item to the top of the stack. |
| 11 | + fn Push(mut *self, item: T) { |
| 12 | + self.items = append(self.items, item) |
| 13 | + } |
| 14 | + |
| 15 | + // Pop removes and returns the item at the top of the stack. |
| 16 | + // The second return value reports whether an item was removed; |
| 17 | + // it is false when the stack is empty. |
| 18 | + fn Pop(mut *self): (item: T, ok: bool) { |
| 19 | + if len(self.items) == 0 { |
| 20 | + return |
| 21 | + } |
| 22 | + last := len(self.items) - 1 |
| 23 | + item = self.items[last] |
| 24 | + self.items = self.items[:last] |
| 25 | + ok = true |
| 26 | + return |
| 27 | + } |
| 28 | + |
| 29 | + // Peek returns the item at the top of the stack without removing it. |
| 30 | + // The second return value reports whether the stack has an item; |
| 31 | + // it is false when the stack is empty. |
| 32 | + fn Peek(*self): (item: T, ok: bool) { |
| 33 | + if len(self.items) == 0 { |
| 34 | + return |
| 35 | + } |
| 36 | + item = self.items[len(self.items)-1] |
| 37 | + ok = true |
| 38 | + return |
| 39 | + } |
| 40 | + |
| 41 | + // Len returns the number of items in the stack. |
| 42 | + fn Len(*self): int { |
| 43 | + return len(self.items) |
| 44 | + } |
| 45 | + |
| 46 | + // Empty reports whether the stack has no items. |
| 47 | + fn Empty(*self): bool { |
| 48 | + return len(self.items) == 0 |
| 49 | + } |
| 50 | +} |
0 commit comments