Stack(LinkedList)

2018-11-19  本文已影响0人  bocsoft
package StackLinkedList

type Node struct {
    data int
    next *Node
}
type Stack struct {
    top *Node
}

func (list *Stack) Push(i int) {
    data := &Node{data: i}
    if list.top != nil {
        data.next = list.top
    }
    list.top = data
}

func (list *Stack) Pop() (int, bool) {
    if list.top == nil {
        return 0, false
    }
    i := list.top.data
    list.top = list.top.next
    return i, true
}

func (list *Stack) Peek() (int, bool) {
    if list.top == nil {
        return 0, false
    }
    return list.top.data, true
}

func (list *Stack) Get() []int {
    var items []int

    current := list.top
    for current != nil {
        items = append(items, current.data)
        current = current.next
    }
    return items
}

func (list *Stack) IsEmpty() bool {
    return list.top == nil
}

func (list *Stack) Empty() {
    list.top = nil
}


package StackLinkedList

import (
    "testing"
)

func TestStack_Empty(t *testing.T) {
    stack := Stack{&Node{1, nil}}
    if !stack.IsEmpty(){
        t.Logf(" I Empty Passed!")
    }

    stack.Push(1)
    i, b := stack.Peek()
    if b && (1 == i){
        t.Logf("push passed!")
    }

    get := stack.Get()
    if len(get) == 2{
        t.Logf("get passed!")
    }
}





上一篇下一篇

猜你喜欢

热点阅读