Skip to content

Commit 2c20e6c

Browse files
committed
Add Stack in Golang
1 parent 880d4db commit 2c20e6c

File tree

3 files changed

+38
-2
lines changed

3 files changed

+38
-2
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2235,8 +2235,8 @@ Com o objetivo de alcançar uma abrangência maior e encorajar novas pessoas a c
22352235
</a>
22362236
</td>
22372237
<td> <!-- Go -->
2238-
<a href="./CONTRIBUTING.md">
2239-
<img align="center" height="25" src="https://cdn.jsdelivr.net/gh/devicons/devicon/icons/github/github-original.svg" />
2238+
<a href="./src/go/stack/stack.go">
2239+
<img align="center" height="25" src="https://cdn.jsdelivr.net/gh/devicons/devicon/icons/go/go-original.svg" />
22402240
</a>
22412241
</td>
22422242
<td> <!-- Ruby -->

src/go/main.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import (
2121
"../go/radixsort"
2222
"../go/selectionsort"
2323
"../go/shellsort"
24+
"../go/stack"
2425
)
2526

2627
func main() {
@@ -100,4 +101,13 @@ func main() {
100101
slice = []int{10, 1000, 100000, 10000000}
101102
fmt.Println("Slice : ", slice)
102103
fmt.Println("CalculatePi : ", calculatepi.CalculatePi(slice))
104+
105+
pilha := stack.Stack[int]{}
106+
pilha.Push(1)
107+
pilha.Push(2)
108+
pilha.Push(3)
109+
pilha.Push(4)
110+
pilha.Pop()
111+
fmt.Printf("Stack: ")
112+
pilha.Show()
103113
}

src/go/stack/stack.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package stack
2+
3+
import "fmt"
4+
5+
// A simple stack using generics
6+
type Stack[T any] struct {
7+
items []T
8+
}
9+
10+
func (stack *Stack[T]) Push(value T) {
11+
stack.items = append(stack.items, value)
12+
}
13+
14+
func (stack *Stack[T]) Pop() T {
15+
n := len(stack.items)
16+
if n <= 0 {
17+
panic("Cannot pop an empty stack!")
18+
}
19+
value := stack.items[n-1]
20+
stack.items = stack.items[:n-1]
21+
return value
22+
}
23+
24+
func (stack *Stack[T]) Show() {
25+
fmt.Printf("%v\n", stack.items)
26+
}

0 commit comments

Comments
 (0)