niedziela, 12 lutego 2023

[Let`s go with golang] Stack Implementation

 Good Night

Today I think and I want write something. I finished study some time ago. When I learn C, I must implemented list (one-way,two-way,stack). Today I write in go so I write code. I write it to long, because I haven't written in a long time. I hope this will change.

Function file:

package elements

import "fmt"

type Element struct {
    Value int
    next  *Element
}

func WriteOut(el Element) {
    fmt.Print(el.Value)
    if el.next != nil {
        fmt.Print(" -> ")
        WriteOut(*el.next)
    } else {
        fmt.Println("")
    }
}
func Create(value int) Element {
    result := Element{Value: value}
    return result
}
func Add(el Element, value int) Element {
    result := Element{Value: value, next: &el}
    return result
}
func Take(el Element) Element {
    return *el.next
}

Main file:

package main

import (
    "fmt"

    stack "com.moles.stack/elements"
)

func main() {
    fmt.Println("Start")
    s := stack.Create(1)
    stack.WriteOut(s)
    s = stack.Add(s, 2)
    stack.WriteOut(s)
    s = stack.Add(s, 3)
    stack.WriteOut(s)
    s = stack.Add(s, 4)
    stack.WriteOut(s)
    s = stack.Take(s)
    stack.WriteOut(s)
    s = stack.Add(s, 5)
    stack.WriteOut(s)
}

Console result:

$ go run .

Start

1

2 -> 1

3 -> 2 -> 1

4 -> 3 -> 2 -> 1

3 -> 2 -> 1

5 -> 3 -> 2 -> 1


----------------SOURCE-------------------------------------------