DATA STRUCTURE AND ALGORITHM (Linked List)

 LINKED LIST


Linked List is a linear data structure. Unlike arrays, linked list elements are not stored at a contiguous location; the elements are linked using pointers.


linkedlist

Why Linked List? 
Arrays can be used to store linear data of similar types, but arrays have the following limitations. 
1) The size of the arrays is fixed: So we must know the upper limit on the number of elements in advance. Also, generally, the allocated memory is equal to the upper limit irrespective of the usage. 
2) Inserting a new element in an array of elements is expensive because the room has to be created for the new elements and to create room existing elements have to be shifted. 

Advantages over arrays 
1) Dynamic size 
2) Ease of insertion/deletion
Drawbacks: 
1) Random access is not allowed. We have to access elements sequentially starting from the first node. So we cannot do binary search with linked lists efficiently with its default implementation.
2) Extra memory space for a pointer is required with each element of the list. 
3) Not cache friendly. Since array elements are contiguous locations, there is locality of reference which is not there in case of linked lists.


The Linked List class contains a reference of Node class type:

class Node {

public:
int data;
Node* next;
};


A simple CPP program to introduce a linked list:

#include <bits/stdc++.h>
using namespace std;

class Node {
public:
int data;
Node* next;
};

int main()
{
Node* head = NULL;
Node* second = NULL;
Node* third = NULL;

// allocate 3 nodes in the heap
head = new Node();
second = new Node();
third = new Node();

head->data = 1; // assign data in first node

head->next = second; // Link first node with the second node

// assign data to second node
second->data = 2;

// Link second node with the third node
second->next = third;

third->data = 3; // assign data to third node
third->next = NULL;

return 0;
}


Linked List Traversal:

#include <bits/stdc++.h>
using namespace std;

class Node {
public:
int data;
Node* next;
};

void printList(Node* n)
{
while (n != NULL) {
cout << n->data << " ";
n = n->next;
}
}

int main()
{
Node* head = NULL;
Node* second = NULL;
Node* third = NULL;

// allocate 3 nodes in the heap
head = new Node();
second = new Node();
third = new Node();

head->data = 1; // assign data in first node
head->next = second; // Link first node with second

second->data = 2; // assign data to second node
second->next = third;

third->data = 3; // assign data to third node
third->next = NULL;

printList(head);

return 0;
}

    Output: 

     1  2  3
Connect with the Author:
Instagram

Comments

Popular posts from this blog

DATA STRUCTURE AND ALGORITHM (Array)

DATA STRUCTURE AND ALGORITHM (Pointer)

DATA STRUCTURE AND ALGORITHM (Structure)