In the third iteration, we will only need to do the following comparisons:
- Compare the first and second nodes
- Compare the second and third nodes
After the third iteration, the third largest value, that is, three, will be set at our desired location, that is, just before node four.
In the fourth, and final, iteration, only the first and second nodes will be compared. The linked list will be sorted in ascending order as follows after the fourth iteration:
Figure 5.28
Let's use GCC to compile the sortlinkedlist.c program as follows:
D:\CBook>gcc sortlinkedlist.c -o sortlinkedlist
If you get no errors or warnings, that means that the sortlinkedlist.c program has been compiled into an executable file, sortlinkedlist.exe. Let's run this executable file as follows:
D:\CBook>./sortlinkedlist
How many elements are there in the linked list ?5
Enter elements in the linked list
3
1
7
4
2
Sorted order is:
1 2 3 4 7
Voilà! We've successfully created and sorted a singly linked list. Now, let's move on to the next recipe!