]> git.lizzy.rs Git - micro.git/blob - stack.go
Really improve syntax file compatibility with nano
[micro.git] / stack.go
1 package main
2
3 // Stack is a simple implementation of a LIFO stack
4 type Stack struct {
5         top  *Element
6         size int
7 }
8
9 // An Element which is stored in the Stack
10 type Element struct {
11         value interface{} // All types satisfy the empty interface, so we can store anything here.
12         next  *Element
13 }
14
15 // Len returns the stack's length
16 func (s *Stack) Len() int {
17         return s.size
18 }
19
20 // Push a new element onto the stack
21 func (s *Stack) Push(value interface{}) {
22         s.top = &Element{value, s.top}
23         s.size++
24 }
25
26 // Pop removes the top element from the stack and returns its value
27 // If the stack is empty, return nil
28 func (s *Stack) Pop() (value interface{}) {
29         if s.size > 0 {
30                 value, s.top = s.top.value, s.top.next
31                 s.size--
32                 return
33         }
34         return nil
35 }
36
37 // Peek lets you see and edit the top value of the stack without popping it
38 func (s *Stack) Peek() *interface{} {
39         if s.size > 0 {
40                 return &s.top.value
41         }
42         return nil
43 }