Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,959 questions

51,901 answers

573 users

How to implement a linked list in Go

1 Answer

0 votes
package main
 
import "fmt"
 
type Node struct {
    prev *Node
    next *Node
    val interface{}
}
 
type LL struct {
    head *Node
    tail *Node
}
 
func (ll *LL) Insert(val interface{}) {
    linklist := &Node {
        next: ll.head,
        val: val,
    }
    if ll.head != nil {
        ll.head.prev = linklist
    }
    ll.head = linklist
 
    ltail := ll.head
    for ltail.next != nil {
        ltail = ltail.next
    }
    ll.tail = ltail
}
 
func (ll *LL) Print() {
    llist := ll.head
    for llist != nil {
        fmt.Printf("%+v - ", llist.val)
        llist = llist.next
    }
    fmt.Println()
}

  
func main() {
    linklist := LL{}
    
    linklist.Insert(6)
    linklist.Insert(1)
    linklist.Insert(87)
    linklist.Insert(34)
    linklist.Insert(982)
    linklist.Insert(7)
    linklist.Insert(3)
    linklist.Insert(99)    
    
    linklist.Print()
    
    fmt.Printf("Head: %v\n", linklist.head.val)
    fmt.Printf("Tail: %v\n", linklist.tail.val)
}




/*
run:

99 - 3 - 7 - 982 - 34 - 87 - 1 - 6 - 
Head: 99
Tail: 6

*/

 



answered Aug 23, 2020 by avibootz
edited Aug 23, 2020 by avibootz
...