| 1 |
package queue |
| 2 |
|
| 3 |
type ( |
| 4 |
Queue struct { |
| 5 |
start, end *node |
| 6 |
length int |
| 7 |
} |
| 8 |
node struct { |
| 9 |
value interface{} |
| 10 |
next *node |
| 11 |
} |
| 12 |
) |
| 13 |
|
| 14 |
|
| 15 |
func New() *Queue { |
| 16 |
return &Queue{nil,nil,0} |
| 17 |
} |
| 18 |
|
| 19 |
func (this *Queue) Dequeue() interface{} { |
| 20 |
if this.length == 0 { |
| 21 |
return nil |
| 22 |
} |
| 23 |
n := this.start |
| 24 |
if this.length == 1 { |
| 25 |
this.start = nil |
| 26 |
this.end = nil |
| 27 |
} else { |
| 28 |
this.start = this.start.next |
| 29 |
} |
| 30 |
this.length-- |
| 31 |
return n.value |
| 32 |
} |
| 33 |
|
| 34 |
func (this *Queue) Enqueue(value interface{}) { |
| 35 |
n := &node{value,nil} |
| 36 |
if this.length == 0 { |
| 37 |
this.start = n |
| 38 |
this.end = n |
| 39 |
} else { |
| 40 |
this.end.next = n |
| 41 |
this.end = n |
| 42 |
} |
| 43 |
this.length++ |
| 44 |
} |
| 45 |
|
| 46 |
func (this *Queue) Len() int { |
| 47 |
return this.length |
| 48 |
} |
| 49 |
|
| 50 |
func (this *Queue) Peek() interface{} { |
| 51 |
if this.length == 0 { |
| 52 |
return nil |
| 53 |
} |
| 54 |
return this.start.value |
| 55 |
} |