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