Linked List using C++ part4

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?
  1. int count()
  2. {
  3. int count=0;
  4. Node *cur;
  5. cur=head;
  6. while(cur!=NULL)
  7. {
  8. cur=cur->next;
  9. count++;
  10. }
  11. return count;
  12. }
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
  1. void sort()
  2. {
  3. Node *cur= head;
  4. int temp;
  5. int counter=count();
  6. for (int i=0; i<counter; i++)
  7. {
  8. cur = head;
  9. while (cur->next!=NULL)
  10. {
  11. if (cur->data > cur->next->data)
  12. {
  13. temp=cur->data;
  14. cur->data=cur->next->data;
  15. cur->next->data=temp;
  16. cur=cur->next;
  17. }
  18. else
  19. cur = cur->next;
  20. }
  21. }
  22. }
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.
  1. ~Linklist ()
  2. {
  3. while(!checkempty())
  4. {
  5. DeleteFirstNode();
  6. }
  7. }
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. Output: Output

Add new comment