forked from TheAlgorithms/Go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stacklinkedlist.go
72 lines (59 loc) · 1.58 KB
/
stacklinkedlist.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
72
// Stack Linked-List
// description: based on `geeksforgeeks` description Stack is a linear data structure which follows a particular order in which the operations are performed.
// The order may be LIFO(Last In First Out) or FILO(First In Last Out).
// details:
// Stack Data Structure : https://www.geeksforgeeks.org/stack-data-structure-introduction-program/
// Stack (abstract data type) : https://en.wikipedia.org/wiki/Stack_(abstract_data_type)
// author [Milad](https://github.com/miraddo)
// see stacklinkedlistwithlist.go, stackarray.go, stack_test.go
package stack
// Node structure
type Node struct {
Val any
Next *Node
}
// Stack has jost top of node and with length
type Stack struct {
top *Node
length int
}
// push add value to last index
func (ll *Stack) push(n any) {
newStack := &Node{} // new node
newStack.Val = n
newStack.Next = ll.top
ll.top = newStack
ll.length++
}
// pop remove last item as first output
func (ll *Stack) pop() any {
result := ll.top.Val
if ll.top.Next == nil {
ll.top = nil
} else {
ll.top.Val, ll.top.Next = ll.top.Next.Val, ll.top.Next.Next
}
ll.length--
return result
}
// isEmpty to check our array is empty or not
func (ll *Stack) isEmpty() bool {
return ll.length == 0
}
// len use to return length of our stack
func (ll *Stack) len() int {
return ll.length
}
// peak return last input value
func (ll *Stack) peak() any {
return ll.top.Val
}
// show all value as an interface array
func (ll *Stack) show() (in []any) {
current := ll.top
for current != nil {
in = append(in, current.Val)
current = current.Next
}
return
}