正在学习go语言中,欢迎提出宝贵意见
import ( "fmt" "sync"
)
type DataNode struct { data interface { } next * DataNode
}
type WorkQueue struct { root * DataNode size int mutex sync. Mutex
}
func NewWorkQueue ( ) * WorkQueue { wq := & WorkQueue{ root: nil , size: 0 } return wq
}
func ( wq * WorkQueue) Add ( data interface { } ) { wq. mutex. Lock ( ) defer wq. mutex. Unlock ( ) if wq. root == nil { wq. root = new ( DataNode) wq. root. data = data } else { dn := new ( DataNode) dn. data = data node := wq. root for node. next != nil { node = node. next } node. next = dn } wq. size++
}
func ( wq * WorkQueue) Pop ( ) interface { } { wq. mutex. Lock ( ) defer wq. mutex. Unlock ( ) if wq. root == nil { return nil } else { node := wq. root v := node. data wq. root = node. next wq. size-- return v }
}
func ( wq * WorkQueue) Size ( ) int { return wq. size
}
func ( wq * WorkQueue) ShowValue ( ) { if wq. root == nil { fmt. Println ( "队列为空队列!" ) } else { size := wq. sizefmt. Println ( "队列元素数:" , size) node := wq. root n := 1 fmt. Printf ( "第%d个元素是:%v\n" , n, node. data) for node. next != nil { node = node. next n++ fmt. Printf ( "第%d个元素是:%v\n" , n, node. data) } }
}