facebook like button

16 June, 2011

Concept of linked lists in C

     You have seen dynamic allocation of memory in C. But that was only introduction. How this is implemented in real life is shown in this post. Imagine the case of scanning some numbers and storing in memory. Now you know that there is something called dynamic memory allocation so you can use that instead of declaring a large array at the start of the program. You can think of scanning a number, then allocating memory for that number and then putting the number in the allocated memory space and repeating the same procedure for next numbers if needed. Your thinking is very good and apreciable but there is a problem that you can face. That is how you will keep track of each and every location allocated dynamically during the execution of the program.
     One solution which can come to your mind is just keep track of first location (just store it's address in a pointer variable) and store address of next location beside it. So this is the situaation in which you dont  This solution is also globally accepted. For this purpose you can create a derrived data-type which would contain a number (or may be more data depending on your need) and a pointer variable to hold the address of next location of data. This pointer is a link between the two nodes ( Each location can be said a node.) This is why these are called linked lists.
     To give you more clear idea of linked lists let me give an analogy. Lets compare arrays and linked lists. An array can be thought as a line of persons so any viewer can easily tell the location of any particular person in the line. He can also judge next person just by seeing the line and the current person because its very obvious. On the other hand linked lists can be think of a bunch of persons which are scattered here and there in a place and every person knows who is the person next to him. No outsider can say anything about their order. In the same way if you want to go to 3rd member of linked list then first of all go to first member take address of second from there, go to second take address of 3rd from there and then go to 3rd. Each time you have to start from first member and then proceed towards the desired member by going through intermediate members.

Remarks:
when you realize that you have got some command on linked list concepts after going through next 3-4 programs, you can have a look on program78 of this blog. This is a good program combining various operations on linked lists.

No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply