Implementing Linked List in Golang With Some Operations
package main
import (
"fmt"
)
type Node struct {
val int
next *Node
}
type LinkedList struct {
head *Node
length int
}
func (l *LinkedList) insert(n *Node) {
currentNode := l.head
n.next = currentNode
l.head = n
l.length++
}
func (l *LinkedList) delete(d int) {
if l.head != nil {
if l.head.val == d {
l.head = l.head.next
}
}
prev := l.head
currentNode := l.head.next
for currentNode != nil {
if currentNode.val == d {
prev.next = currentNode.next
}
prev = prev.next
currentNode = currentNode.next
}
}
func (l *LinkedList) traverse() {
currentNode := l.head
for currentNode != nil {
swap(currentNode, currentNode.next)
currentNode = currentNode.next.next
}
}
func swap(left *Node, right *Node) {
left.val, right.val = right.val, left.val
}
func (l *LinkedList) print() {
currentNode := l.head
for currentNode != nil {
fmt.Println(currentNode.val)
currentNode = currentNode.next
}
}
func (l *LinkedList) sort() {
currentNode := l.head
for currentNode != nil {
next := currentNode.next
for next != nil {
if currentNode.val < next.val {
swap(currentNode, next)
}
next = next.next
}
currentNode = currentNode.next
}
}
func main() {
l := &LinkedList{head: &Node{val: 5}}
l.insert(&Node{val: 10})
l.insert(&Node{val: 22})
l.insert(&Node{val: 25})
l.insert(&Node{val: 4})
l.insert(&Node{val: 15})
fmt.Println("Values => ")
l.print()
l.sort()
fmt.Println("After Sorting Values => ")
l.print()
l.traverse()
fmt.Println("After Traverse Values => ")
l.print()
l.delete(15)
fmt.Println("After Deleting 15 Values => ")
l.print()
}
Output of the programme will be like below#
dj@ubuntu:/host/project/go/src/gotest$ go run linkedlist.go
Values =>
15
4
25
22
10
5
After Sorting Values =>
25
22
15
10
5
4
After Traverse Values =>
22
25
10
15
4
5
After Deleting 15 Values =>
22
25
10
4
5
linked-list is kind of data structure we will implement today#
We have studied about linked list in our degree college but have you ever implemented after that, i think never only when it is asked in any interviews.
May be you know about linkedlist but i will quickly explain again. It is kind of datastructure which contains nodes. Nodes is like a container which contains data as well as the memory address of next node.
we can dynamically attach new node to last node or first node. unlike array whose size is fixed at define time there is nothing like size in linked list it is dynamic array of data.
so deletion and insertion in linked list is faster than array.
if there is advantage then there will be disadvantage, linked list consumes more memory and for any operation we have two iterate through each node to find the correct one which increases complexities.
there are doubly linkedlist as well which we will implement in future blog post.