Principle of linked list
Unidirectional linked list is a kind of linear list, which is actually composed of nodes. A linked list has an indefinite number of nodes. The data stored in the memory is not continuous. The data stored in the memory is scattered. Each Node can only and only it can know the storage location of the next Node. Each Node of N forms a one-way linked list. Each Node records the data of this Node and the next Node. There is only one Head exposed to the outside. All our operations on the linked list are carried out directly or indirectly through its Head Node.
code implementation
Define linked list structure
package main import ( "fmt" ) type HeroNode struct { no int name string nickname string next *HeroNode }
Insert linked list
func InsertHeroNode(head *HeroNode,newHeroNode *HeroNode) { //Find the appropriate node temp := head flag:=true //Compare the inserted node no with the next node no of temp for { if temp.next==nil{//At the end of the list break }else if temp.next.no>newHeroNode.no{ //Note that newheronode should be inserted after temp break }else if temp.next.no==newHeroNode.no{ //It means that there is already in the list flag=false break } temp=temp.next } if !flag{ fmt.Println("Sorry, it already exists no=",newHeroNode.no) return }else { newHeroNode.next=temp.next temp.next=newHeroNode } }
Delete linked list node
func DelHerNode(head *HeroNode,id int ){ temp:=head flag:=false //Find the node you want to delete, for { if temp.next==nil{//At the end of the list break }else if temp.next.no==id{ //It means that there is already in the list flag=true break } temp=temp.next } if flag{ temp.next=temp.next.next }else{ fmt.Println("To delete ID non-existent",id) } }
Show linked list nodes
func ListHerNode(head *HeroNode){ temp:=head //First, judge whether the list is an empty list for{ if temp.next==nil{ fmt.Println("Empty emulsion") return } for{ fmt.Printf("[%d,%s,%s]==>",temp.next.no, temp.next.name,temp.next.nickname) //After judging whether the list is linked or not temp=temp.next if temp.next==nil{ break } } } }
Main function implementation
func main(){ //Create a header node first head:=&HeroNode{} //Bedstead a new Heronode hero1:=&HeroNode{ no:1, name:"name of a fictitious monkey with supernatural powers", nickname:"Monkey King", } hero2:=&HeroNode{ no:2, name:"Eight Precepts", nickname:"canopy ", } hero3:=&HeroNode{ no:3, name:"Monk Sha", nickname:"you 're incompetent", } InsertHeroNode(head,hero1) InsertHeroNode(head,hero2) InsertHeroNode(head,hero3) ListHerNode(head) fmt.Println() //DelHerNode(head,2) ListHerNode(head) }