/*
* A generalized stack. This is as close as we get to a generic stack.
*/
package genstack
/*
* Node for the linked structure. This is private, since the client
* never needs to refer to it.
*/
type node struct {
data interface {}
next *node
}
// This is the stack type. The type Stack is exported, but the field
// head is not, so the client cannot look inside the stack.
type Stack struct {
head *node
}
// Push method for the stack. Notice that the receiver, stack, is
// effectively a pointer to a pointer to node.
func (stack *Stack) Push(d interface {}) {
nn := new(node)
nn.data = d
nn.next = stack.head
stack.head = nn
}
// Pop method for stack. If the stack is not empty, return the top
// item and true. If it's empty, return 0 and false, without changing
// the stack.
func (stack *Stack) Pop() (v interface {}, ok bool) {
if stack.head == nil {
return nil, false
} else {
v = stack.head.data
stack.head = stack.head.next
ok = true
return
}
}
// Empty method.
func (stack *Stack) Empty() bool {
return stack.head == nil
}