rewrite stack with pointers

pull/7/head
Alexander Kuleshov 7 years ago
parent 0f22fe5c1b
commit 248647cbff
No known key found for this signature in database
GPG Key ID: 11DB55FD14934DB6

@ -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
}

@ -2,24 +2,20 @@ package stack
import "testing"
func Test_Stack(t *testing.T) {
stack := New()
func TestStack(t *testing.T) {
var stack *Stack = New()
stack.Push(1)
stack.Push(2)
stack.Push(3)
stack.Push(4)
stack.Push(5)
stack.Push(6)
stack.Push(7)
if stack.Length() != 3 {
t.Error("[Error] stack length is wrong")
}
stack.Pop()
if stack.Length() != 2 {
t.Error("[Error] stack length is wrong after pop")
}
for i := 5; i > 0; i-- {
item := stack.Pop()
if stack.Peek() != 6 {
t.Error("[Error] stack Peek is wrong")
if item != i {
t.Error("TestStack failed...", i)
}
}
}

Loading…
Cancel
Save