Linked List is a linear data structure. Unlike arrays, linked list elements are not stored at a contiguous location. The element are linked using pointers.
Why Linked list is used:-
Arrays can be used to store linear data of similar types, but arrays have the following limitations.
- Array's size is fixed. So we must know the highest limit of the array in advance. So we must declare the size of the array first and elements there after.
- Inserting a new element is very expensive because the room has to be be created for the new elements and shift the existing elements.
Ex:- Suppose we have arrays in sorted order i.e. [1,2,3,4,6,7] and we have to insert new element i.e. [5] in the array. So in order to maintain elements in sorted order, we have to place that element after suitable element. In this situation we have to shift the element i.e. [6,7] by position 1.
Now we saw the arrays limitations. Let's understand the advantages of the Linked List over array.
Advantages of Linked List:-
- Linked List are in Dynamic in size.
- In Linked List, there is Ease of Insertion and deletion of the node.
- No memory wastage.
- Linked List is traversal and have reverse traversing.
Disadvantages of Linked List:-
- We cannot access elements randomly. We have to access elements sequentially from first element or Node.
- Linked List requires extra memory space for pointers.
A Linked List is represented by a pointer to the first node of the linked list. The first node is called "head". If the linked list is empty, then the value of the head is Null.
Each node is consist of atleast two components:-
- Data
- Pointer points to the next node
- we create the object i.e. list1 and call the LinkedList class.
- we assigned the list1.head value to Node class and pass the argument that is data of the node
- we created 3 Nodes.
- after that we assigned the next value of the first Node to the second Node and next of second to third Node.
First we created a temp variable and then start for loop to traverse the Linked List element one by one.
We print the data and then assign next Node value to be printed.
Let us see the full code:-
Comments
Post a Comment