golang Golang使用链表实现基本堆栈的示例
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang Golang使用链表实现基本堆栈的示例相关的知识,希望对你有一定的参考价值。
package main
import (
"fmt"
"sync"
)
type Node struct {
value int
next *Node
}
type StackOfInts struct {
head *Node
length int
sync.Mutex
}
func (s *StackOfInts) Push(n int) {
s.Lock()
defer s.Unlock()
this := s.head
s.head = &Node{
value: n,
next: this,
}
s.length++
}
func (s *StackOfInts) Pop() int {
s.Lock()
defer s.Unlock()
popped := s.head
s.head = s.head.next
s.length--
return popped.value
}
func (s *StackOfInts) Len() int {
s.Lock()
defer s.Unlock()
return s.length
}
func (s *StackOfInts) IsEmpty() bool {
s.Lock()
defer s.Unlock()
return s.head == nil
}
func NewStack() *StackOfInts {
return &StackOfInts{
head: nil,
}
}
func main() {
s := NewStack()
s.Push(10)
s.Push(20)
s.Push(30)
s.Push(40)
for s.Len() > 0 {
fmt.Println(s.Pop())
}
fmt.Println(s.IsEmpty())
}
golang 在go中注册堆栈实现
package main
//go program to implement a portable VM
import (
"fmt"
"reflect"
)
type RegisterStack struct {
registers map[int]interface{}
//stores records of amount of registers and locations
records map[string]int
}
//creates a new register set
func CreateRStk() RegisterStack {
rs := RegisterStack{registers:make(map[int]interface{}), records:map[string]int{"last":-1, "next":0}}
return rs
}
//initializes a new register space
func (rs RegisterStack) Addregister() {
rs.registers[rs.records["next"]] = nil
rs.records["last"] += 1
rs.records["next"] += 1
}
//deletes the last register in the stack
func (rs RegisterStack) Removeregister() {
delete(rs.registers, rs.records["last"])
rs.records["last"] -= 1
rs.records["next"] -= 1
}
//sets a value to a register
func (rs RegisterStack) SetValue(val interface{}, register int) {
if register >= 0 && register < rs.records["next"] {
rs.registers[register] = val
}
}
//gets a value from a register
func (rs RegisterStack) GetValue(register int) interface{} {
return rs.registers[register]
}
func main(){
vartest := CreateRStk()
vartest.Addregister()
vartest.Addregister()
vartest.SetValue("foo", 0)
vartest.SetValue(3, 1)
//type assertion
extract := vartest.GetValue(1).(int)
extract += 2
vartest.SetValue(extract, 1)
fmt.Println(reflect.TypeOf(extract))
fmt.Println(vartest)
}
以上是关于golang Golang使用链表实现基本堆栈的示例的主要内容,如果未能解决你的问题,请参考以下文章
手撸golang 基本数据结构与算法 链表
【golang】HashMap原理和实现
golang 在go中注册堆栈实现
用golang实现的单向链表
Golang之实现(链表)
手撸golang 基本数据结构与算法 图的搜索 深度优先/广度优先