题解 | 【模板】队列
【模板】队列
https://www.nowcoder.com/practice/afe812c80ad946f4b292a26dd13ba549
package main
import (
"fmt"
)
type node struct {
val int
next *node
}
type Queue struct {
head *node
tail *node
}
func NewQueue() *Queue {
return &Queue{}
}
func (q *Queue) push(val int) {
n := &node{val: val, next: nil}
if q.head == nil {
q.head = n
q.tail = q.head
} else {
q.tail.next = n
q.tail = n
}
}
func (q *Queue) pop() (int, bool) {
if q.head == nil {
return 0, false
} else {
val := q.head.val
q.head = q.head.next
if q.head == nil {
q.tail = nil
}
return val, true
}
}
func (q *Queue) front() (int, bool) {
if q.head == nil {
return 0, false
} else {
return q.head.val, true
}
}
func main() {
var operation string
var num int
q := NewQueue()
for {
n, _ := fmt.Scan(&operation)
if n == 0 {
break
} else {
switch operation {
case "push":
_, _ = fmt.Scan(&num)
q.push(num)
case "pop":
val, ok := q.pop()
if ok {
fmt.Println(val)
} else {
fmt.Println("error")
}
case "front":
val, ok := q.front()
if ok {
fmt.Println(val)
} else {
fmt.Println("error")
}
}
}
}
}
360集团公司福利 409人发布