Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#5

Open
lsyf opened this issue Oct 14, 2019 · 0 comments
Open

#5

lsyf opened this issue Oct 14, 2019 · 0 comments

Comments

@lsyf
Copy link
Owner

lsyf commented Oct 14, 2019

1. 需求

  • 栈(简单)

2. 设计

  • 结构
    1. 数据改动频繁,使用链表实现
    2. 方案二:使用container/list实现,无容量限制(代码
  • 行为
    1. push,pop,peak
  • 边界条件
    1. 栈满了,添加值
    2. 栈为空,获取值

3. 代码

package list

import (
	"container/list"
	"fmt"
	"strings"
)

type Stack struct {
	list *list.List
}

func NewStack() *Stack {
	list := list.New()
	return &Stack{list}
}

func (stack *Stack) Push(value interface{}) {
	stack.list.PushBack(value)
}

func (stack *Stack) Pop() interface{} {
	e := stack.list.Back()
	if e != nil {
		stack.list.Remove(e)
		return e.Value
	}
	return nil
}

func (stack *Stack) Peak() interface{} {
	e := stack.list.Back()
	if e != nil {
		return e.Value
	}
	return nil
}

func (stack *Stack) Len() int {
	return stack.list.Len()
}

func (stack *Stack) String() (str string) {
	data := make([]string, 0, stack.Len())
	for e := stack.list.Front(); e != nil; e = e.Next() {
		data = append(data, fmt.Sprintf("%v", e.Value))
	}

	str = strings.Join(data, ",")
	str = "[" + str + "]"
	return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
数据结构
Awaiting triage
Development

No branches or pull requests

1 participant