Implementing Stack & Queue in go (golang)
First lets define the interface for Stack,
type Stack interface {
Push(value interface{})
Pop() (interface{}, bool)
Peek() (interface{}, bool)
HasNext() bool
Len() int
}
We can use the doubly linked from "container/list" to implement our Stack,
just import "container/list"
Define a type which implements our Stack interface,
type stack struct{
list *list.List
}
We can have constructor which returns the stack instance,
func NewStack() Queue{
return &stack{list: list.New()}
}
We can leverage the PushFront() and Front() list methods to push values to the head
and get hold of the first element
func (this *stack) Push(value interface{}){
this.list.PushFront(value)
}
The Front() method return a pointer to Element type in list package,
the actual value in list is stored in Element's Value field.
func (this *stack) Pop() (interface{}, bool){
e := this.list.Front()
if e == nil{
return nil,false
}
this.list.Remove(e)
return e.Value,true
}
similarly we can implement Peek(), we just skip the Remove() from Pop.
Len() and HasNext() can leverage the Len() method of list,
func (this *stack) Len() int{
return this.list.Len()
}
func (this *stack) HasNext() bool{
return this.list.Len() != 0
}
On the same lines we can implement Queue by leveraging
list.PushBack() method in Push() of Queue method.
No comments:
Post a Comment