Created
July 24, 2012 19:13
-
-
Save valtyriel/3171985 to your computer and use it in GitHub Desktop.
Implementation of a stack: a singly-linked list where items are added and removed from the same end, in first-in, last-out order.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package stack | |
type element struct { | |
// Pointer to the next element in the list. | |
// The last element has next = nil. | |
next *Element | |
// The stack to which this element belongs. | |
stack *Stack | |
// The contents of this stack element. | |
value interface{} | |
} | |
// Stack represents a singly-linked list. | |
// The zero value for Stack is an empty stack ready to use. | |
type Stack struct { | |
front *element | |
len int | |
} | |
func New() *Stack { | |
return new(Stack) | |
} | |
// Init initializes or clears a stack. | |
func (s Stack) Init() Stack { | |
s.front = nil | |
s.len = 0 | |
return s | |
} | |
// Len returns the number of elements in the stack. | |
func (s Stack) Len() int { return s.len } | |
// Push adds a new element to the top of the stack. | |
func (s *Stack) Push(value interface{}) *Element { | |
e := new(Element) | |
e.Value = value | |
e.stack = s | |
e.next = s.Front | |
} | |
// Pop returns the value of the top element of the stack. | |
func (s *Stack) Pop() interface{} { | |
e := s.front | |
s.front = nil | |
s.len-- | |
return e.value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment