Linked List is a data structure that contains group of nodes connected in a sequential manner with a pointer. Linked list and arrays are similar since they both store collections of data in a sequential manner.
Linked list can behave as a dynamic array. The size of an array is fixed, so to use more than its capacity, one may have to resize the array or create large enough array to fit in all elements which could result in wasting unused memory space.
An array allocates memory for all its elements lumped together as one block of memory. In contrast, a linked list allocates space for each element separately in its own block of memory called a "linked list element" or "node". The list gets is overall structure by using pointers to connect all its nodes together like the links in a chain.
Each node contains two fields: a "data" field to store whatever element type the list holds for its client, and a "next" field which is a pointer used to link one node to the next node.
Advantages of Linked list over array:
Disadvantages of linked list:
In linkedlist, each object coud lbe referred as a node. For simplicity sake, we could consider a Linkedlist storing integer object.
class Node {
int data; // store the integer value
Node next; // store the pointer to the next element
}
Most commonly used Linkedlists are Singly LinkedList and Doubly LinkedList. Above code example represents a Single Linkedlist. Doubly Linkedlist - Singly linkedlist has a forward pointer and moves in one direction. Doubly linkedlist has an extra pointer generally referred as previous and the list could move in either direction.
class Node {
int data; // store the integer value
Node next; // store the pointer to the next element
Node prev; //store the previous pointer to the next element
}
Operations on linkedlist
Here is the code Operations on Linkedlist