Using Golang to implement chained storage for stacks

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Stack is like a water cup in-first out, the chain of the stack in the back element of the next always point to the advanced element, the top element of the stack is always the same as the last element to go in

Type Elem int

node element structure

Type Node struct {

Data Elem

Next *node

}

Stacklink Stack

Type Stacklink struct {

Top *node//Stack tops elements

length int

}

Initstack initialization of a stack, stack advanced after the

Func (S *stacklink) Initstack () {

S.top = Nil

}

Push adds a STACK element

Func (S *stacklink) Push (data Elem) {

Create a Node

Node: = new (node)

Node.data = Data

Node.next = S.top

S.top = node

s.length++

}

Pop pops up an element

Func (S *stacklink) Pop (e *elem) error {

If S.empty () {

return errors. New ("Empty Stack")

}

*e = S.top.data

Node: = S.top

S.top = Node.next

s.length--

return Nil

}

Empty stack

Func (S *stacklink) Empty () bool {

return s.top = = Nil

}

The number of elements in the Length stack

Func (S *stacklink) Length () int {

Return s.length

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.