美文网首页
Stack(LinkedList)

Stack(LinkedList)

作者: bocsoft | 来源:发表于2018-11-19 14:22 被阅读0次
    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!")
        }
    }
    
    
    
    
    
    

    相关文章

      网友评论

          本文标题:Stack(LinkedList)

          本文链接:https://www.haomeiwen.com/subject/qmzofqtx.html