rewrite stack with pointers
parent
0f22fe5c1b
commit
248647cbff
@ -1,61 +1,47 @@
|
|||||||
package stack
|
package stack
|
||||||
|
|
||||||
type Stack struct {
|
type StackItem struct {
|
||||||
st []interface{}
|
item interface{}
|
||||||
len int
|
next *StackItem
|
||||||
}
|
|
||||||
|
|
||||||
func New() *Stack {
|
|
||||||
stack := &Stack{}
|
|
||||||
stack.st = make([]interface{}, 1)
|
|
||||||
stack.len = 0
|
|
||||||
return stack
|
|
||||||
}
|
|
||||||
|
|
||||||
func (stack *Stack) Length() int {
|
|
||||||
return stack.len
|
|
||||||
}
|
|
||||||
|
|
||||||
func (stack *Stack) Pop() {
|
|
||||||
stack.st = stack.st[1:]
|
|
||||||
stack.len -= 1
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (stack *Stack) Peek() interface{} {
|
// Stack is a base structure for LIFO
|
||||||
return stack.st[0]
|
type Stack struct {
|
||||||
|
sp *StackItem
|
||||||
|
depth uint64
|
||||||
}
|
}
|
||||||
|
|
||||||
func (stack *Stack) IsEmpty() bool {
|
// Initialzes new Stack
|
||||||
return (stack.len == 0)
|
func New() *Stack {
|
||||||
}
|
var stack *Stack = new(Stack)
|
||||||
|
|
||||||
func (stack *Stack) Push(value interface{}) {
|
stack.depth = 0
|
||||||
add(stack, value)
|
return stack
|
||||||
}
|
}
|
||||||
|
|
||||||
func add(slice *Stack, value interface{}) {
|
// Pushes a given item into Stack
|
||||||
slice.len += 1
|
func (stack *Stack) Push(item interface{}) {
|
||||||
var tmpSlice []interface{} = make([]interface{}, slice.len)
|
stack.sp = &StackItem{item: item, next: stack.sp}
|
||||||
if slice.len == 0 {
|
stack.depth++
|
||||||
slice.st[0] = value
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for i := 0; i < slice.len; i++ {
|
// Deletes top of a stack and return it
|
||||||
tmpSlice[i] = 0
|
func (stack *Stack) Pop() interface{} {
|
||||||
|
if stack.depth > 0 {
|
||||||
|
item := stack.sp.item
|
||||||
|
stack.sp = stack.sp.next
|
||||||
|
stack.depth--
|
||||||
|
return item
|
||||||
}
|
}
|
||||||
|
|
||||||
for i := 0; i < slice.len; i++ {
|
return nil
|
||||||
if i == 0 {
|
|
||||||
tmpSlice[0] = value
|
|
||||||
} else {
|
|
||||||
tmpSlice[i] = slice.st[i-1]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if i == slice.len-1 {
|
// Returns top of a stack without deletion
|
||||||
break
|
func (stack *Stack) Peek() interface{} {
|
||||||
}
|
if stack.depth > 0 {
|
||||||
|
return stack.sp.item
|
||||||
}
|
}
|
||||||
|
|
||||||
slice.st = tmpSlice
|
return nil
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue