生活随笔
收集整理的這篇文章主要介紹了
[数据结构]之链表
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
[數據結構]之鏈表
?1 描述
鏈表:對于當前鏈表中元素,除了存儲本身的值,還存儲有指示后面元素的地址(通常是指針或引用)。
節點:每一個鏈表的元素稱為一個節點。
2 數據結構
節點Node,鏈表Linklist
1)節點屬性
存儲的數據 data
指向下一元素的指針 next
2)鏈表屬性
鏈表的起始節點 begin
當前長度
3)操作
Get(index)獲取元素
Insert(index,elem) 插入元素
Delete(index) 刪除第i個元素
3 go語言實現
package mainimport ("fmt")/**
定義節點*/
type Node struct {Data stringNext *
Node}/**
定義鏈表*/
type LinkList struct {Begin *
NodeLength int}/**
獲取順序表的第index元素*/
func (list *LinkList) Get(index int) (*
Node, error) {if list.Length == 0 || index < 0 || index > list.Length-1
{return nil, fmt.Errorf(
"the index %d Out Of Bounds", index)}var retElem *
NoderetElem =
list.Begin//
循環節點,查到下一個元素for i := 1; i <= index; i++
{retElem =
retElem.Next}return retElem, nil}/**
插入順序表元素,在第index位置*/
func (list *LinkList) Insert(index int, elem *
Node) error {if index < 0 || index >
list.Length {return fmt.Errorf(
"the index %d Out Of Bounds", index)}//
是否插入到第一個位置if index ==
0 {elem.Next =
list.Beginlist.Begin =
elemlist.Length++
return nil}//
修改前一節點和插入元素的指向curElem, err := list.Get(index - 1
)if err !=
nil {fmt.Println(err)return err}elem.Next =
curElem.NextcurElem.Next =
elemlist.Length++
return nil}/**
刪除順序表元素,在第index位置*/
func (list *
LinkList) Delete(index int) error {if list.Length ==
0 {return fmt.Errorf(
"the list is empty")}if index < 0 || index >
list.Length {return fmt.Errorf(
"the index %d Out Of Bounds", index)}//
是否刪除第一個位置if index ==
0 {list.Begin =
list.Begin.Nextlist.Length--
return nil}//
修改后一節點和刪除元素的指向curElem, err := list.Get(index - 1
)if err !=
nil {fmt.Println(err)return err}curElem.Next =
curElem.Next.Nextlist.Length--
return nil}func main() {list := &
LinkList{}list.Insert(0, &Node{Data:
"AAAAA"})list.Insert(1, &Node{Data:
"BBBBB"})list.Insert(2, &Node{Data:
"CCCCC"})list.Delete(1
)for i := 0; i < list.Length; i++
{elem, _ :=
list.Get(i)fmt.Printf("get elem %d value:%v\n", i, elem.Data)}} ?
轉載于:https://www.cnblogs.com/sxt102400/p/3234242.html
總結
以上是生活随笔為你收集整理的[数据结构]之链表的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。