/
main.go
68 lines (60 loc) · 1.66 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
//Main Package to demostrate Queue data structure
package main
import (
"container/list"
"fmt"
)
// In order to group our data we use type - struct
type dataStack struct {
stack *list.List
}
// Push : Function to add elements into the stack
func (d *dataStack) Push(value string) {
d.stack.PushFront(value)
}
// Pop : Function to remove elements from the stack
func (d *dataStack) Pop() error {
if d.stack.Len() > 0 {
element := d.stack.Front()
d.stack.Remove(element)
}
return fmt.Errorf("Pop Error: Stack is Empty")
}
// Peek : Return the last Element in the state as per LIFO logic
func (d *dataStack) Peek() (string, error) {
if d.stack.Len() > 0 {
if value, ok := d.stack.Front().Value.(string); ok {
return value, nil
}
return "", fmt.Errorf("Peek Error: Stack data type is incorrect")
}
return "", fmt.Errorf("Peek Error: Stack is empty")
}
//Size : Return the integer value corresponding to the size of the Stack
func (d *dataStack) Size() int {
return d.stack.Len()
}
//isEmpty: Return boolean value based on stack's contents
func (d *dataStack) IsEmpty() bool {
return d.stack.Len() == 0
}
//Main: Starting point of this GO Program
func main() {
dataObject := &dataStack{
stack: list.New(),
}
fmt.Printf("Push: Data-1\n")
dataObject.Push("Data-1")
fmt.Printf("Push: Data-2\n")
dataObject.Push("Data-2")
fmt.Printf("Is Empty: %t\n", dataObject.IsEmpty())
fmt.Printf("Size: %d\n", dataObject.Size())
for dataObject.Size() > 0 {
topVal, _ := dataObject.Peek()
fmt.Printf("Front: %s\n", topVal)
fmt.Printf("Pop: %s\n", topVal)
dataObject.Pop()
}
fmt.Printf("Is Empty: %t\n", dataObject.IsEmpty())
fmt.Printf("Size: %d\n", dataObject.Size())
}