github.com/iainanderson83/datastructures@v0.0.4-0.20191103204413-889e20b53bcf/queue/queue.go (about)

     1  package queue
     2  
     3  import (
     4  	"container/list"
     5  
     6  	"github.com/iainanderson83/datastructures/stack"
     7  )
     8  
     9  var (
    10  	_ Queue = &ArrQueue{}
    11  	_ Queue = NewListQueue()
    12  	_ Queue = &StackQueue{}
    13  )
    14  
    15  // Queue is an interface for a classic queue datastructure
    16  type Queue interface {
    17  	Enqueue(interface{})
    18  	Dequeue() interface{}
    19  	Len() int
    20  }
    21  
    22  type ArrQueue struct {
    23  	s []interface{}
    24  }
    25  
    26  func (a *ArrQueue) Enqueue(v interface{}) {
    27  	if v == nil {
    28  		return
    29  	}
    30  
    31  	a.s = append(a.s, v)
    32  }
    33  
    34  func (a *ArrQueue) Dequeue() interface{} {
    35  	if len(a.s) == 0 {
    36  		return nil
    37  	}
    38  
    39  	v := a.s[0]
    40  	a.s[0] = nil // GC
    41  	a.s = a.s[1:]
    42  	return v
    43  }
    44  
    45  func (a *ArrQueue) Len() int { return len(a.s) }
    46  
    47  type ListQueue struct {
    48  	l *list.List
    49  }
    50  
    51  func NewListQueue() *ListQueue {
    52  	return &ListQueue{list.New()}
    53  }
    54  
    55  func (l *ListQueue) Enqueue(v interface{}) {
    56  	l.l.PushBack(v)
    57  }
    58  
    59  func (l *ListQueue) Dequeue() interface{} {
    60  	if l.l.Len() == 0 {
    61  		return nil
    62  	}
    63  	e := l.l.Front()
    64  	return l.l.Remove(e)
    65  }
    66  
    67  func (l *ListQueue) Len() int { return l.l.Len() }
    68  
    69  type StackQueue struct {
    70  	s1    stack.Stack
    71  	s2    stack.Stack
    72  	count int
    73  }
    74  
    75  func (s *StackQueue) Enqueue(v interface{}) {
    76  	if v == nil {
    77  		return
    78  	}
    79  
    80  	s.count++
    81  	s.s1.Push(v)
    82  }
    83  
    84  func (s *StackQueue) Dequeue() interface{} {
    85  	if s.s1.Peek() == nil && s.s2.Peek() == nil {
    86  		return nil
    87  	}
    88  
    89  	if s.s2.Peek() == nil {
    90  		for {
    91  			v := s.s1.Pop()
    92  			if v == nil {
    93  				break
    94  			}
    95  			s.s2.Push(v)
    96  		}
    97  	}
    98  
    99  	s.count--
   100  	return s.s2.Pop()
   101  }
   102  
   103  func (s *StackQueue) Len() int { return s.count }