-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack_Linkedlist.go
71 lines (57 loc) · 931 Bytes
/
stack_Linkedlist.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
69
70
71
package main
import "fmt"
type Node struct {
value int
next *Node
}
type Stack struct {
top *Node
length int
}
func (stack *Stack) push(value int) {
newNode := Node{}
newNode.value = value
ptr := stack.top
stack.top = &newNode
stack.top.next = ptr
stack.length++
}
func (stack *Stack) pop() {
if stack.length == 0 {
fmt.Println("Stack is emtpy")
return
}
stack.top = stack.top.next
stack.length--
return
}
func (stack *Stack) peek() {
if stack.length == 0 {
fmt.Println("Stack is empty")
return
}
fmt.Println(stack.top.value)
}
func (stack *Stack) print() {
if stack.length == 0 {
fmt.Println("Stack is empty")
return
}
ptr := stack.top
for i := 0; i < stack.length; i++ {
fmt.Print(ptr.value, " ")
ptr = ptr.next
}
fmt.Printf("\nSize: %d\n", stack.length)
}
func main() {
s := Stack{}
s.push(4)
s.push(1)
s.push(9)
s.peek()
s.print()
s.pop()
s.peek()
s.print()
}