Created
December 7, 2019 14:47
-
-
Save tesarwijaya/767795eaac795edaa7cb11a369da17cb to your computer and use it in GitHub Desktop.
Stack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
// Stack ... | |
type Stack struct { | |
Items []int64 | |
Top int | |
} | |
// Push element to stack | |
func (s *Stack) Push(v int64) { | |
s.Top = s.Top + 1 | |
s.Items[s.Top] = v | |
} | |
// Pop element from stack | |
func (s *Stack) Pop() int64 { | |
v := s.Items[s.Top] | |
s.Top = s.Top - 1 | |
s.Items = s.Items[:len(s.Items)-1] | |
return v | |
} | |
// PrintStack ... | |
func (s *Stack) PrintStack() { | |
fmt.Println("Items: ", s.Items) | |
} | |
// InitStack ... | |
func InitStack(max int64) *Stack { | |
return &Stack{ | |
Items: make([]int64, max), | |
Top: -1, | |
} | |
} | |
// Main ... | |
func main() { | |
s := InitStack(5) | |
s.Push(1) | |
s.Push(2) | |
s.Push(3) | |
s.Push(4) | |
s.Push(5) | |
s.PrintStack() | |
s.Pop() | |
s.PrintStack() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment