[数据结构]之栈 ##1 描述 栈:后进先出的数据结构。栈是封底的,只能从一个方向写入读出。 栈的实现有两种,基于顺序表方式和基于链表方式。 栈的场景:比如浏览器的返回场景。 顺序表实现: 1)在顺序表的基础上创建栈。 2)使用arr[0]作为栈底,arr[MAXSIZE]为栈顶。Top当栈顶元素位置标志,从0-MAXSIZE之间。 3)局限:分配的空间固定。 链表实现: 1)链表的基础上创建栈。 2)使用末尾节点作为栈底,头节点为栈顶。Top为栈顶元素位置标志。 ##2 数据结构 * 顺序表实现: 1)属性 元素数组 elemets 栈顶元素位置 top 元素个数 length(值为top+1) 2)操作 NewStack 初始化,建立空栈 Push 压栈 Pop 出栈 * 链表实现 1 属性 栈顶节点 top 元素个数 length 2 操作 NewStack 初始化,建立空栈 Push 压栈 Pop 出栈 ##3 go语言实现 1 顺序表实现: package main import ( "fmt" ) const CAP = 20 type Stack struct { elements [CAP]string top int `栈顶位置` length int `元素个数` } func NewStack() *Stack { return &Stack{top: -1, length: 0} } /* * 压栈 */ func (list *Stack) Push(elem string) error { if list.top == CAP-1 { return fmt.Errorf("the list is full") } //插入到栈顶元素上 list.top++ list.length++ list.elements[list.top] = elem return nil } /* * 出栈 */ func (list *Stack) Pop() (string, error) { if list.top == -1 { return "", fmt.Errorf("the list is empty") } //获取需要出栈的元素 elem := list.elements[list.top] list.top-- list.length-- return elem, nil } func main() { list := NewStack() list.Push("AAAAA") list.Push("BBBBB") list.Push("CCCCC") list.Push("DDDDD") for list.length > 0 { elem, _ := list.Pop() fmt.Println("elem:", elem) } } 2 链表实现 package main import ( "fmt" ) /* * 定义节点 */ type Node struct { Data string Next *Node } /* * 定义栈 */ type Stack struct { Top *Node Length int } func NewStack() *Stack { return &Stack{Top: nil, Length: 0} } /* * 压栈 */ func (list *Stack) Push(data string) error { node := &Node{Data: data, Next: list.Top} list.Top = node list.Length++ return nil } /* * 出栈 */ func (list *Stack) Pop() (string, error) { if list.Length == 0 { return "", fmt.Errorf("the list is empty") } node := list.Top list.Top = node.Next list.Length-- return node.Data, nil } func main() { list := NewStack() list.Push("AAAAA") list.Push("BBBBB") list.Push("CCCCC") list.Push("DDDDD") list.Push("EEEEE") for list.Length > 0 { elem, _ := list.Pop() fmt.Println("elem:", elem) } }