Adjust the single linked list and stack interface based on the previous implementation. Move the size variable to the list.
type Stack struct {
list *SinglyLinkedList
}
func NewStack(a) *Stack {
return &Stack{
list: &SinglyLinkedList{},
}
}
func (o *Stack) Len(a) int {
return o.list.Len()
}
func (o *Stack) IsEmpty(a) bool {
return o.list.Len() == 0
}
func (o *Stack) Push(v interface{}) {
o.list.AddToHead(v)
}
func (o *Stack) Peek(a) interface{} {
if o.IsEmpty() {
panic("Stack is empty")}return o.list.Head().V
}
func (o *Stack) Pop(a) {
if o.IsEmpty() {
panic("Stack is empty")
}
o.list.RemoveHead()
}
// Single linked list node
type SLLNode struct {
V interface{}
Next *SLLNode
}
/ / singly linked lists
type SinglyLinkedList struct {
head *SLLNode
size int
}
func (o *SinglyLinkedList) Len(a) int {
return o.size
}
func (o *SinglyLinkedList) AddToHead(v interface{}) {
o.head = &SLLNode{
V: v,
Next: o.head,
}
o.size++
}
func (o *SinglyLinkedList) Head(a) *SLLNode {
return o.head
}
func (o *SinglyLinkedList) RemoveHead(a) {
if o.head == nil {
panic("SinglyLinkedList. head is nil")
}
o.head = o.head.Next
o.size--
}
Copy the code