栈(LIFO)
package main
import (
"fmt"
"sync"
)
/*
使用 golang 实现栈
栈是一种LIFO(Last In First Out) 的数据结构,可以封装一个slice实现
*/
type Stack struct {
s []int
Mutex sync.Mutex
}
func (self *Stack) Push(value int) {
self.Mutex.Lock()
defer self.Mutex.Unlock()
self.s = append(self.s, value)
}
// 先取出最后一个元素,再缩减slice
func (self *Stack) Pop() int {
self.Mutex.Lock()
defer self.Mutex.Unlock()
value := self.s[len(self.s) - 1]
self.s = self.s[:len(self.s) - 1]
return value
}
func (self *Stack) IsEmpty() bool {
self.Mutex.Lock()
defer self.Mutex.Unlock()
return len(self.s) == 0
}
func (self *Stack) Size() int {
self.Mutex.Lock()
defer self.Mutex.Unlock()
return len(self.s)
}
func main() {
stack := &Stack{}
stack.Push(0)
stack.Push(1)
stack.Push(2)
stack.Push(3)
stack.Push(4)
stack.Push(5)
fmt.Println(stack.IsEmpty())
fmt.Println(stack.Size())
}
队列(FIFO)
package main
import (
"sync"
"fmt"
)
/*
golang 实现 队列
队列是一种FIFO(First In First Out) 的数据结构 可以使用slice 实现
*/
type Queue struct {
queue []int
Mutex sync.Mutex
}
func (self *Queue) Push(value int) {
self.Mutex.Lock()
defer self.Mutex.Unlock()
self.queue = append(self.queue, value)
}
// 取出slice第一个元素,再调整 slice
func (self *Queue) Pop() int {
self.Mutex.Lock()
defer self.Mutex.Unlock()
value := self.queue[0]
self.queue = self.queue[1:]
return value
}
func (self *Queue) IsEmpty() bool {
self.Mutex.Lock()
defer self.Mutex.Unlock()
return len(self.queue) == 0
}
func (self *Queue) Size() int {
self.Mutex.Lock()
defer self.Mutex.Unlock()
return len(self.queue)
}
func main() {
q := &Queue{}
q.Push(0)
q.Push(1)
q.Push(2)
fmt.Println(q.Pop())
fmt.Println(q.Pop())
fmt.Println(q.Pop())
fmt.Println(q.IsEmpty())
fmt.Println(q.Size())
}