Bài tập: Stack với pointer receiver
Cài đặt một stack số nguyên:
type Stack struct { /* ... */ }
func (s *Stack) Push(v int)
func (s *Stack) Pop() (int, bool) // false nếu stack rỗng
func (s *Stack) Peek() (int, bool) // xem đỉnh, không lấy ra
func (s *Stack) Len() intYêu cầu: zero value dùng được ngay (var s Stack hoặc s := &Stack{}), không cần constructor.
Input là chuỗi lệnh push x, pop, peek, len. Với pop/peek chương trình in giá trị hoặc empty.
NOTE
Bạn chỉ viết phần code trong khung soạn thảo — package main, hàm main đọc input/in kết quả đã có sẵn. Các package đã import: fmt. Không thêm import khác.
Examples
Example 1
Input
push 1 push 2 peek pop len
Expected output
2 2 1
Example 2
Input
pop peek len
Expected output
empty empty 0
1 hidden test · Limit 2 s · 256 MB
type Stack struct {
// TODO: thêm field
}
func (s *Stack) Push(v int) {}
func (s *Stack) Pop() (int, bool) { return 0, false }
func (s *Stack) Peek() (int, bool) { return 0, false }
func (s *Stack) Len() int { return 0 }
Comments