Linked List (continued)
In this tutorial, you will learn the
1. Code for calculating number of elements in linked list.
2. Code for sorting of a linked list.
3. Code of destructor of linked list.
What is the code for calculating number of elements in a linked list?
In above code, an integer is made with initial value equal to zero. We make a pointer and make it equal to head which means that it points to first element. Then, we enter a loop and go till end and increment integer during every iteration.
What is the code for sorting of linked list?
An ordered linked list is a linked list in which data is arranged in ascending order. Sometimes, you need an ordered linked list for some tasks
Node *cur= head;
for (int i=0; i<counter; i++)
cur = head;
if (cur->data > cur->next->data)
cur = cur->next;
Given above is the code for sorting of a linked list. First of all, we make a pointer and make it equal to head and then a temporary integer is made and it is given value equal to number of elements in the linked list. Next we enter nested loops and first loop starts from 0 to number of elements and the other loop starts from first element and end at last element. Inner loop always starts from first and goes till last for every iteration of outer loop. During each outer loop iteration, the biggest data goes to one extreme and hence after all the iterations, linked list is sorted.
What is the code for destructor of a linked list?
If you recall that while adding nodes in a linked list, dynamic nodes were added. As there was an operator of “new”. As dynamic memory must me deleted, so there must be a destructor in linked list.
Here we delete every node one by one until the linked list is empty.
Note: C++ codes along merged with the previous linked list codes are given along with these. In next tutorial , I will try to wind up basic functions of linked list like insertion in middle, deletion from middle and copy constructor.