github.com/dnutiu/simplFT@v0.0.0-20181023061248-df4b14cdce57/server/stack.go (about)

     1  package server
     2  
     3  // Stack interface
     4  type Stack interface {
     5  	// Push pushes an item to the stack. Returns an error if it fails.
     6  	Push(item interface{})
     7  	// Pop retrieves an item from the stack and removes it.
     8  	Pop() interface{}
     9  	// Top peeks at an item from the stack.
    10  	Top() interface{}
    11  	// IsEmpty returns bool indicating if the stack is empty.
    12  	IsEmpty() bool
    13  	// Capacity returns the capacity of the stack.
    14  	Capacity() int
    15  	// Size returns the size of the stack
    16  	Size() int
    17  }
    18  
    19  // StringStack is a stack that holds string objects
    20  type StringStack struct {
    21  	index    int
    22  	capacity int
    23  	items    []string
    24  }
    25  
    26  // MakeStringStack initializes a new StringStack pointer.
    27  func MakeStringStack(capacity int) *StringStack {
    28  	st := StringStack{}
    29  
    30  	st.capacity = capacity
    31  	st.index = 0
    32  	st.items = make([]string, capacity, capacity)
    33  
    34  	return &st
    35  }
    36  
    37  // Push pushes an item of type string to the stack.
    38  func (st *StringStack) Push(item interface{}) {
    39  	if st.index == st.Capacity() {
    40  		panic(StackOverflowError)
    41  	}
    42  
    43  	value, ok := item.(string)
    44  	if ok == false {
    45  		panic(StackInvalidTypeError)
    46  	}
    47  
    48  	st.items[st.index] = value
    49  	st.index++
    50  }
    51  
    52  // Pop returns the last pushed item from the stack and removes it
    53  func (st *StringStack) Pop() interface{} {
    54  	if st.Size() == 0 {
    55  		panic(StackUnderflowError)
    56  	}
    57  	st.index--
    58  	return st.items[st.index]
    59  }
    60  
    61  // Top return the last pushed item from the stack without removing it.
    62  func (st *StringStack) Top() interface{} {
    63  	if st.Size() == 0 {
    64  		panic(StackUnderflowError)
    65  	}
    66  	return st.items[st.index-1]
    67  }
    68  
    69  // IsEmpty returns true if the stack contains no items.
    70  func (st *StringStack) IsEmpty() bool {
    71  	return st.Size() == 0
    72  }
    73  
    74  // Capacity returns the maximum items the stack can hold.
    75  func (st *StringStack) Capacity() int {
    76  	return st.capacity
    77  }
    78  
    79  // Size returns number of items the stack currently holds.
    80  func (st *StringStack) Size() int {
    81  	return st.index
    82  }
    83  
    84  // Items returns an array of the stack items as a copy.
    85  func (st StringStack) Items() []string {
    86  	return st.items
    87  }