本篇文章将会使用数据结构中的栈来实现音乐播放器的音乐添加和删除功能,分别使用切片和链表实现它。
type song struct {
value interface{}
next *song
}
type Stack struct {
top *song
size int
}
func (stack *Stack) add_song(value interface{}) {
stack.top = &song{value: value, next: stack.top}
fmt.Printf("the top song is %s\n", stack.top.value)
stack.size++
}
实现介绍:
func (stack *Stack) delete_song() {
if stack.top.next != nil {
stack.top = stack.top.next
fmt.Printf("the top song is %s\n", stack.top.value)
stack.size--
} else {
stack.size = 0
fmt.Printf("it‘s an empty playlist\n")
}
}
type ItemType interface{}
type Stack_Slice struct {
song []ItemType
rwLock sync.RWMutex
}
func (stack *Stack_Slice) add_song_slice(value interface{}) {
stack.rwLock.Lock()
stack.song = append(stack.song, value)
stack.rwLock.Unlock()
}
实现介绍:
func (stack *Stack_Slice) delete_song_slice() {
if len(stack.song) != 0 {
stack.rwLock.Lock()
stack.song = stack.song[0 : len(stack.song)-1]
stack.rwLock.Unlock()
} else {
fmt.Printf("It‘s a empty playlist")
}
}
实现介绍:
Tips: 栈的链表/切片实现,其复杂度均为 O(1)
原文:https://www.cnblogs.com/xingzheanan/p/14644689.html