パッケージメイン
import(
"fmt"
)
type Object interface {}
type Node struct { data Object //次のデータフィールドを定義 * Node //アドレスフィールドを定義(次のテーブルのアドレスを指す)} type List struct { headNode * Node //ヘッドノード
}
//それが空の単一リンクリストであるかどうかを判断する
func(this * List)IsEmpty()bool {// IsEmptyメソッドを作成すると、型はboolになります。
this.headNode == nil {//単一リンクリストが空であると判断した場合、ヘッドノードが空であると判断するだけで済みます。
return true
} else { return false } } //リストの長さを取得func(this * List)Length()int { //リンクリストのヘッドノードを取得 cur:= this.headNode //カウンターを定義し、初期値は0 count:= 0 for cur!= nil { //ヘッドノードが空でない場合、count ++ count ++ } return count } //リストの先頭から要素を追加しますfunc(this * List)Add(data Object)* Node { ノード:=&ノード{データ:データ} node.next = this.headNode
this.headNode = node
return node
}
//開始链表尾部添加
func(this * List)Append(data Object){ node:=&Node {data:data} if this.IsEmpty(){ this.headNode = node } else { cur:= this.headNode for cur.next!= nil { cur = cur.next } cur.next = node } } //在链表中指定点得要素func(this * List)Insert(index int、data Object) { if index <0 { this.Add(data) } else if index> this.Length(){ this.Append(data) } else { pre:= this.headNode
count:= 0
for count <(index-1){ pre = pre.next count ++ } node:=&Node {data:data} node.next = pre.next pre.next = node } } //リンクされたすべてをトラバースするlist Node func(this * List)ShowList(){ if!this.IsEmpty(){ cur:= this.headNode for { fmt.Printf( "\ t%v"、cur.data) if cur.next!= nil { cur = cur.next } else { break } } } } //リンクリストに要素があるかどうかを確認します
func(this * List)Contain(data Object)bool { cur:= this.headNode for cur!= nil { if cur.data == data { return true } cur = cur.next } return false } // in Go The forステートメントが同じではない//指定された位置の要素を削除するfunc(this * List)RemoveAtIndex(index int){ pre:= this.headNode if index <= 0 {//インデックスが0または0未満の場合、次にヘッドノード this.headNode = pre.nextを削除します
} else if index> this.Length(){ fmt.Printf( "超出链表NL度") return } else { count:= 0 for count!=(index-1)&& pre.next!= nil { count ++ pre = pre。 next } pre.next = pre.next.next } } //删除指定位置要素func(this * List)Remove(data Object){ pre:= this.headNode if pre.data == data { this.headNode = pre .next } else { for pre.next!= nil { if pre.next.data == data { pre.next = pre.next.next } else { pre = pre.next
}
}
}
}
// func deletenode(head * listNode、val int)* ListNode { // if head == nil { // return head //} // return nil //} func main(){ list:= List {} list.Append(1) list.Append(2) list.Append(3) list.Append(4) list.Append(5) list.Append(6) list.Append(7) list.Append(8) //fmt.Print( "链表%d \ n"、list.Length()) fmt.Print( "链表List当前值是:") list.ShowList() t:= list.Length() fmt.Print( t)}