Wednesday, July 7, 2021

Create singly linked list in golang

A linked list is a linear data structure, in which the elements are linked to next element using pointers.

The following illustration would help to understand it:  


Let's implement this  in golang:


To create a linked listed we first have to create Node with data and next pointing to the another Node.

To create Node we need two fields, data and next.

Step1:

type Node struct{
data int
next *Node
}

Step2:

Now define Linkedlist struct:

type LinkedList struct{
head *Node
}

Step3:

Now that we have defined structs that we need, let's try creating Node and linkedlist .

func main(){
node1 := new(Node)
fmt.Println(node1)
}

Here when we create new node it will have default values of each field which here is 0 and nil.
so printing node1 would give the output as:

&{0 <nil>}

We now need a way to initialise Node struct with our values.

Step4:

Writing a function to do this:
func (n *Node) NewNode(data int, next *Node){
n.data = data
n.next = next
}

Step5:

with this new function we will change the code in main() function

func main(){
node1 := new(Node)
fmt.Println(node1)
node1.NewNode(1, nil)
fmt.Println(node1)
}

Now we the second print statement gives node1 output as &{1 <nil>}

The reason that `next` field is showing it as nil is because we just created one Node and there is no other Node where we can link this node1 to.


Step6:

Let's created linkedlist with this Node:

func main(){
node1 := new(Node)
fmt.Println(node1)
node1.NewNode(1, nil)
fmt.Println(node1)
llist := new(LinkedList)
llist.head = node1
}

Now we have created linked list with it's head pointing to our Node1.

Our linked list would now be like this:



Step7:

Let's create Node2 and update our linkedlist.

func main(){
node1 := new(Node)
fmt.Println(node1)
node1.NewNode(1, nil)
fmt.Println(node1)
llist := new(LinkedList)
llist.head = node1
node2 := new(Node)
node2.NewNode(2, nil)
llist.head.next = node2
}

The last three lines of code we have created new Node which is same as step5, 

now that we have to update our existing linkedlist the update that we have to do is head is pointing to Node1 i.e. head = Node1 now Node1.next has to be pointing to Node2.

Node1 is head here so head.next = node2 will update our linked list as below:



Step8:

For the last step let's create another Node and update our linked list:

func main(){
node1 := new(Node)
fmt.Println(node1)
node1.NewNode(1, nil)
fmt.Println(node1)
llist := new(LinkedList)
llist.head = node1
node2 := new(Node)
node2.NewNode(2, nil)
llist.head.next = node2
node3 := new(Node)
node3.NewNode(3, nil)
llist.head.next.next = node3
}

This will have our linked list as in first figure.

The complete code is:






No comments:

Post a Comment