Skip to content

Instantly share code, notes, and snippets.

@rof20004
Created March 9, 2024 11:32
Show Gist options
  • Save rof20004/8c8a4bd7532e63542a4104c5dc1d68f5 to your computer and use it in GitHub Desktop.
Save rof20004/8c8a4bd7532e63542a4104c5dc1d68f5 to your computer and use it in GitHub Desktop.
queue and stack home made
// You can edit this code!
// Click here and start typing.
package main
import "fmt"
func enqueue(a []int, elem int) []int {
return append([]int{elem}, a...)
}
func dequeue(a []int) []int {
if len(a) == 0 {
return a
}
return a[:len(a)-1]
}
func push(a []int, elem int) []int {
return append(a, elem)
}
func pop(a []int) ([]int, int) {
if len(a) == 0 {
return a, -1
}
n := a[len(a)-1]
return a[:len(a)-1], n
}
func peek(a []int) int {
if len(a) == 0 {
return -1
}
return a[len(a)-1]
}
func main() {
fmt.Println("Queue Example")
a := []int{}
fmt.Println(a)
a = enqueue(a, 5)
fmt.Println(a)
a = enqueue(a, 10)
a = enqueue(a, 15)
fmt.Println(a)
a = dequeue(a)
fmt.Println(a)
a = dequeue(a)
fmt.Println(a)
a = dequeue(a)
fmt.Println(a)
a = dequeue(a)
fmt.Println(a)
fmt.Println("")
fmt.Println("Stack Example")
b := []int{}
fmt.Println(b)
b = push(b, 1)
fmt.Println(b)
b = push(b, 3)
fmt.Println(b)
b = push(b, 5)
fmt.Println(b)
var e int
b, e = pop(b)
fmt.Println(b, e)
b, e = pop(b)
fmt.Println(b, e)
b, e = pop(b)
fmt.Println(b, e)
b, e = pop(b)
fmt.Println(b, e)
b = push(b, 3)
fmt.Println(b)
e = peek(b)
fmt.Println(e)
b, e = pop(b)
fmt.Println(b, e)
e = peek(b)
fmt.Println(e)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment