Single Linked list

Single Linked List

  • Linked list a linear data structure.
  • Linked list contains group of nodes in a sequence.
  • Each node is divided into two parts, data/value and address of next node

Advantages

  • Dynamic in nature and allocates memory when it is required.
  • Easy to implement insertion and deletion operation
  • Stacks, queues, tress, graphs etc can be easily implemented

Disadvantages

  • It is not easy to reverse the linked list
  • If we are at a not and wants to go with previour node, then we can not do it in single step
  • No elements can be accessed randomly, it requires to access sequentially.

Program:

// Create a single linked list and print element of list
package main

import "fmt"

// Node structure
type Node struct {
	Value int
	Next  *Node
}

func create() *Node {
	// Create head of linked list
	// Head has value 0 and points to nil i.e. no next node
	head := &Node{Value: 0, Next: nil}

	// Create a variable points to current node
	current := head

	// Create next nodes
	for i := 5; i <= 100; i += 5 {
		// Create a new node
		nextNode := &Node{Value: i, Next: nil}
		// Link new node to the head of current node
		current.Next = nextNode
		// Change current node pointer
		current = nextNode
	}

	return head
}

func print(list *Node) {
    for current := list; current != nil; current = current.Next {
	fmt.Printf("%d ", current.Value)
    }
}

func main() {
	var list = create()
	print(list)
}

Output

0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100

Leave a Reply

Your email address will not be published. Required fields are marked *