stack.go
1 // Copyright (c) 2024-2026 Tencent Zhuque Lab. All rights reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 // 15 // Requirement: Any integration or derivative work must explicitly attribute 16 // Tencent Zhuque Lab (https://github.com/Tencent/AI-Infra-Guard) in its 17 // documentation or user interface, as detailed in the NOTICE file. 18 19 // Package parser 实现栈结构 20 package parser 21 22 import ( 23 "container/list" 24 ) 25 26 // Stack represents a LIFO (Last In First Out) data structure 27 // 使用Go标准库中的list实现栈结构 28 type Stack struct { 29 list *list.List 30 } 31 32 // NewStack creates and initializes a new Stack 33 // 创建并初始化一个新的栈 34 func NewStack() *Stack { 35 return &Stack{list: list.New()} 36 } 37 38 // pop removes and returns the top element from the stack 39 // 从栈顶移除并返回元素,如果栈为空则返回nil 40 func (stack *Stack) pop() interface{} { 41 e := stack.list.Back() 42 if e != nil { 43 stack.list.Remove(e) 44 return e.Value 45 } 46 return nil 47 } 48 49 // push adds a new element to the top of the stack 50 // 将新元素添加到栈顶 51 func (stack *Stack) push(v interface{}) { 52 stack.list.PushBack(v) 53 } 54 55 // isEmpty checks if the stack has no elements 56 // 检查栈是否为空 57 func (stack *Stack) isEmpty() bool { 58 return stack.list.Len() == 0 59 } 60 61 // top returns the top element without removing it from the stack 62 // 返回栈顶元素但不移除它,如果栈为空则返回nil 63 func (stack *Stack) top() interface{} { 64 e := stack.list.Back() 65 if e != nil { 66 return e.Value 67 } 68 return nil 69 }