GOLANG 实现Stack和Queue

来源:互联网 发布:百度搜索关键词优化 编辑:程序博客网 时间:2024/05/18 03:51

最近在学习go语言,go是google公司开发的一种服务器端语言,原生提供的go程具有强大的并发能力,语言简洁、干净,没有太多语法糖,但其表达能力一点都不比其他语言弱。

go语言中有指针的概念,可以非常方便的实现Stack和Queue,我的实现里没有使用go库中的list,下面就是实现代码:

Queue实现

type Node struct {    data interface{}    next *Node}type Queue struct {    head *Node    end  *Node}func NewQueue() *Queue {    q := &Queue{nil, nil}    return q}func (q *Queue) push(data interface{}) {    n := &Node{data: data, next: nil}    if q.end == nil {        q.head = n        q.end = n    } else {        q.end.next = n        q.end = n    }    return}func (q *Queue) pop() (interface{}, bool) {    if q.head == nil {        return nil, false    }    data := q.head.data    q.head = q.head.next    if q.head == nil {        q.end = nil    }    return data, true}

Stack实现

type Stack struct {    head *Node}func NewStack() *Stack {    s := &Stack{nil, 0}    return s}func (s *Stack) Push(data interface{}) {    n := &Node{data: data, next: s.head}    s.head = n}func (s *Stack) Pop() (interface{}, bool) {    n := s.head    if s.head == nil {        return nil, false    }    s.head = s.head.next    return n.data, true}
原创粉丝点击