Golang中List的实现方法示例详解

2020-01-28 12:19:22王振洲

遍历

下面normalIndex函数的作用返回一个正常逻辑的Index,例如处理好一些越界问题:


func (l *List) normalIndex(index int) int {
 if index > l.length-1 {
 index = l.length - 1
 }

 if index < -l.length {
 index = 0
 }
 // 将给定的index与length做取余处理
 index = (l.length + index) % l.length
 return index
}

如下的函数为获取指定范围内的数据,根据传入的参数需要指定start和end,最后返回的应该是一个切片或者数组,具体类型未知:


func (l *List) Range(start, end int) []interface{} {
 // 获取正常的start和end
 start = l.normalIndex(start)
 end = l.normalIndex(end)
 // 声明一个interface类型的数组
 res := []interface{}{}
 // 如果上下界不符合逻辑,返回空res
 if start > end {
 return res
 }
 
 sNode := l.index(start)
 eNode := l.index(end)
 // 起始点和重点遍历
 for n := sNode; n != eNode; {
 // res的append方式
 res = append(res, n.Value)
 n = n.next
 }
 res = append(res, eNode.Value)
 return res
}

ok,以上即为Go中List的数据结构的实现方式,通过本节,能够学习到许多Go的语法特性。个人认为学习编程,语法是最简单的,应该利用最短的时间在,最有效的掌握。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对易采站长站的支持。