Go語言列表List獲取元素的4種方式
Golang的列表元素的獲取可以使用內置的 Front 函數獲取頭結點,使用 Back 函數獲取尾結點,使用 Prev 獲取前一個結點,使用 Next 獲取下一個結點。
1、獲取列表頭結點
Front() *Element
package main
import (
"container/list"
"fmt"
)
func main() {
fmt.Println("嗨客網(www.haicoder.net)")
//使用列表內置的 Front() 函數,獲取列表的頭結點
listHaiCoder := list.New()
listHaiCoder.PushFront("Hello")
listHaiCoder.PushFront("HaiCoder")
listHaiCoder.PushFront("嗨客網")
element := listHaiCoder.Front()
fmt.Println("Front =", element.Value)
}
使用列表內置的 Front() 函數,獲取列表的頭結點。
2、獲取列表尾結點
Back () *Element
package main
import (
"container/list"
"fmt"
)
func main() {
fmt.Println("嗨客網(www.haicoder.net)")
//使用列表內置的 Back() 函數,獲取列表的尾結點
listHaiCoder := list.New()
listHaiCoder.PushFront("Hello")
listHaiCoder.PushFront("HaiCoder")
listHaiCoder.PushFront("嗨客網")
element := listHaiCoder.Back()
fmt.Println("Back =", element.Value)
}
使用列表內置的 Back() 函數,獲取列表的尾結點。
3、獲取上一個結點
Prev() *Element
package main
import (
"container/list"
"fmt"
)
func main() {
fmt.Println("嗨客網(www.haicoder.net)")
//使用列表內置的 Prev() 函數,獲取列表的上一個結點
listHaiCoder := list.New()
listHaiCoder.PushFront("Hello")
element := listHaiCoder.PushFront("HaiCoder")
listHaiCoder.PushFront("嗨客網")
preElement := element.Prev()
fmt.Println("preElement =", preElement.Value)
}
使用列表內置的 Prev() 函數,獲取列表的上一個結點。
4、獲取下一個結點
Next() *Element
package main
import (
"container/list"
"fmt"
)
func main() {
fmt.Println("嗨客網(www.haicoder.net)")
//使用列表內置的 Next() 函數,獲取列表的下一個結點
listHaiCoder := list.New()
listHaiCoder.PushFront("Hello")
element := listHaiCoder.PushFront("HaiCoder")
listHaiCoder.PushFront("嗨客網")
nextElement := element.Next()
fmt.Println("nextElement =", nextElement.Value)
}
使用列表內置的 Next() 函數,獲取列表的下一個結點。
到此這篇關于Go語言列表List獲取元素的4種方式的文章就介紹到這了,更多相關Go 列表List獲取元素內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
gin通過go build -tags實現(xiàn)json包切換及庫分析
這篇文章主要為大家介紹了gin通過go build -tags實現(xiàn)json包切換及庫分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-09-09
golang?四則運算計算器yacc歸約手寫實現(xiàn)
這篇文章主要為大家介紹了golang?四則運算?計算器?yacc?歸約的手寫實現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-07-07

