packagemainimport("errors""fmt")// Stack represents a stack that holds elements of type int. typeStackstruct{elements[]int}// NewStack creates and returns a new Stack. funcNewStack()*Stack{return&Stack{elements:[]int{}}}// Push adds an element to the top of the stack. func(s*Stack)Push(elementint){s.elements=append(s.elements,element)}// Pop removes and returns the element at the top of the stack. // If the stack is empty, it returns an error. func(s*Stack)Pop()(int,error){ifs.IsEmpty(){return0,errors.New("stack is empty")}index:=len(s.elements)-1element:=s.elements[index]s.elements=s.elements[:index]returnelement,nil}// Peek returns the element at the top of the stack without removing it. // If the stack is empty, it returns an error. func(s*Stack)Peek()(int,error){ifs.IsEmpty(){return0,errors.New("stack is empty")}returns.elements[len(s.elements)-1],nil}// IsEmpty checks if the stack is empty. func(s*Stack)IsEmpty()bool{returnlen(s.elements)==0}funcmain(){stack:=NewStack()// Push elements onto the stack stack.Push(1)stack.Push(2)stack.Push(3)// Peek the top element top,err:=stack.Peek()iferr!=nil{fmt.Println(err)}else{fmt.Println("Top element:",top)}// Pop elements from the stack for!stack.IsEmpty(){element,err:=stack.Pop()iferr!=nil{fmt.Println(err)}else{fmt.Println("Popped element:",element)}}// Verify that the stack is empty ifstack.IsEmpty(){fmt.Println("Stack is empty")}}
packagemainimport("errors""fmt")// Node represents a node in the linked list. typeNodestruct{valueintnext*Node}// Stack represents a stack that holds elements of type int. typeStackstruct{top*Node}// NewStack creates and returns a new Stack. funcNewStack()*Stack{return&Stack{}}// Push adds an element to the top of the stack. func(s*Stack)Push(valueint){newNode:=&Node{value:value}ifs.top!=nil{newNode.next=s.top}s.top=newNode}// Pop removes and returns the element at the top of the stack. // If the stack is empty, it returns an error. func(s*Stack)Pop()(int,error){ifs.IsEmpty(){return0,errors.New("stack is empty")}value:=s.top.values.top=s.top.nextreturnvalue,nil}// Peek returns the element at the top of the stack without removing it. // If the stack is empty, it returns an error. func(s*Stack)Peek()(int,error){ifs.IsEmpty(){return0,errors.New("stack is empty")}returns.top.value,nil}// IsEmpty checks if the stack is empty. func(s*Stack)IsEmpty()bool{returns.top==nil}funcmain(){stack:=NewStack()// Push elements onto the stack stack.Push(1)stack.Push(2)stack.Push(3)// Peek the top element top,err:=stack.Peek()iferr!=nil{fmt.Println(err)}else{fmt.Println("Top element:",top)}// Pop elements from the stack for!stack.IsEmpty(){element,err:=stack.Pop()iferr!=nil{fmt.Println(err)}else{fmt.Println("Popped element:",element)}}// Verify that the stack is empty ifstack.IsEmpty(){fmt.Println("Stack is empty")}}