Exforsys

Home arrow Technical Training arrow C Tutorials

Singly Linked List Example Program

Page 3 of 3
Author: Exforsys Inc.     Published on: 29th May 2006    |   Last Updated on: 24th Jun 2011

C Programming - Linked Lists

For demonstration of singly linked lists, we have high scores for a game example. This is quite contrived as an array would clearly be better for this but it works well for illustrating linked list implementation.

Ads

What features do we need for this high scores list? We need to be able to create a list of players' names, the associated score; we want the results sorted from greatest score to least score.

Sample Code
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. // sample_game.c Exforsys tutorial.  This is one way
  6. // to fix the order problem, and also, the program isn't
  7. // working as advertised.  The function 'findposition()' isn't
  8. // working as intended in the version supplied in Exforsys
  9. // tutorials : It was returning position==1 each time, such
  10. // that addend() could never be called.  I added explanations
  11. // and diagnostics such that you can see how the process
  12. // works when it operates correctly.  There are many ways to
  13. // accomplish this and many stylistic points that could have
  14. // been addressed, but I didn't want to get carried away.
  15. // Besides, those exercises likely should be left to the student
  16. // who might also like to try other dataset test cases to produce
  17. // a more exhaustive test scenario.  [Ernie Cordell 10November2011]
  18.  
  19. //The node for a linked list
  20. struct llnode
  21. {
  22.     char name[10];
  23.     int score;
  24.     struct llnode *next;
  25. };
  26.  
  27. //Linked list for high scores and number of nodes for inserting in middle.
  28. struct llnode *head = NULL;
  29. int listlen = 0;
  30.  
  31. //Function that adds a new node to the beginning of a linked list.
  32. void addfront(char name[], int score)
  33. {
  34.     printf("Calling addfront for %s.\n", name);
  35.     struct llnode *tempnode;
  36.  
  37.     //Create the new node and copy data.
  38.     tempnode = (struct llnode *)malloc(sizeof(struct llnode));
  39.     strcpy(tempnode->name, name);
  40.     tempnode->score = score;
  41.  
  42.     //2 cases: beginning of empty list or beginning of unempty list.
  43.     if (head == NULL)
  44.     {
  45.         head = tempnode;
  46.         head->next = NULL;
  47.  
  48.     }
  49.     else
  50.     {
  51.         //Insert the new node before current head, then make the new node the head.
  52.         tempnode->next = head;
  53.         head = tempnode;
  54.     }
  55. }
  56.  
  57. //Function that adds a new node to the end of a linked list.
  58. void addend(char name[], int score)
  59. {
  60.     printf("Calling addend for %s.\n", name);
  61.     struct llnode *tempnode = (struct llnode *)malloc(sizeof(struct llnode));
  62.     struct llnode *currentnode = tempnode;
  63.  
  64.     //Create the new node and copy data.
  65.     strcpy(tempnode->name, name);
  66.     tempnode->score = score;
  67.  
  68.     //Traverse the list to the last node.
  69.     if (head == NULL)
  70.     {
  71.         head = tempnode;
  72.         tempnode->next = NULL;
  73.     }
  74.     else
  75.     {
  76.         currentnode = head;
  77.         while (currentnode->next != NULL)
  78.         {
  79.             currentnode = currentnode->next;
  80.         }
  81.         //Set the new node's pointer to NULL.
  82.         tempnode->next = NULL;
  83.         //Set the last node pointer's next to the new node.
  84.         currentnode->next = tempnode;
  85.     }
  86. }
  87.  
  88. //determines which position in the list a node should be placed. Not related to
  89. int findposition(int score)
  90. {
  91.     printf("Calling findposition  .  .  .  \n");
  92.     struct llnode *currentnode;
  93.     int position = 1;
  94.     //If the list is not empty, traverse it.
  95.     printf("The address of head is %p.\n", head);
  96.     currentnode = head;
  97.     if (head != NULL)
  98.     {
  99.         do
  100.         {
  101.             //If the new score is greater than the saved score at the node, then we
  102.             //want to insert here.
  103.             printf("Temp score: %d, Node score: %d.\n",
  104.                    score, currentnode->score);
  105.             if (score >= currentnode->score)
  106.                 return position;
  107.  
  108.             //Otherwise traverse and track position.
  109.             currentnode = currentnode->next;
  110.             position++;
  111.         }
  112.         while (currentnode/*->next */ != NULL);
  113.     }
  114.     return position;
  115. }
  116.  
  117. //Adds a new node by determining where in the list it should go.
  118. void addNode(char name[], int score)
  119. {
  120.     printf("\ntCalling addNode  .  .  .  \n");
  121.     int currentpos = 1;
  122.     int position = findposition(score);
  123.     printf("Position is %d, listlen is %d.\n", position, listlen);
  124.     struct llnode *tempnode = (struct llnode *)malloc(sizeof(struct llnode));
  125.     struct llnode *previousnode = tempnode;
  126.     struct llnode *currentnode;
  127.  
  128.     currentnode = head;
  129.  
  130.     if (position == 1)
  131.     {
  132.         //Add to beginning of list.
  133.         addfront(name, score);
  134.         listlen++;
  135.  
  136.     }
  137.     else if (position > listlen)
  138.     {
  139.         //Add to end of list.
  140.         addend(name, score);
  141.         listlen++;
  142.  
  143.     }
  144.     else
  145.     {
  146.         //Add somewhere in the middle of the list.
  147.         while (currentpos < position)
  148.         {
  149.             //traverse the list until we find the location for the new node.
  150.             currentpos++;
  151.             previousnode = currentnode;
  152.             currentnode = currentnode->next;
  153.         }
  154.         strcpy(tempnode->name, name);
  155.         tempnode->score = score;
  156.  
  157.         previousnode->next = tempnode;
  158.         printf("Adding %s after %s and before %s.\n", tempnode->name,
  159.                previousnode->name, currentnode->name);
  160.         tempnode->next = currentnode;
  161.         listlen++;
  162.     }
  163. }
  164.  
  165. //Prints entire list.
  166. void printList()
  167. {
  168.     printf("tCalling printList  .  .  .  \n");
  169.     struct llnode *currentnode;
  170.  
  171.     currentnode = head;
  172.  
  173.     while (currentnode != NULL)
  174.     {
  175.         printf("%s:", currentnode->name);
  176.         printf("%d", currentnode->score);
  177.         printf("\n");
  178.         currentnode = currentnode->next;
  179.     }
  180. }
  181.  
  182. int main(void)
  183. {
  184.     char player1[] = {"Jon B."};
  185.     char player2[] = {"Tom D."};
  186.     char player3[] = {"Jesse M."};
  187.     char player4[] = {"Todd"};
  188.     char player5[] = {"Matt"};
  189.     int scores[] = {150, 100, 1000, 400, 275};
  190.  
  191.     addNode(player1, scores[0]);
  192.     addNode(player2, scores[1]);
  193.     addNode(player3, scores[2]);
  194.     addNode(player4, scores[3]);
  195.     addNode(player5, scores[4]);
  196.     printList();
  197.     struct llnode* current = NULL;
  198.     while (head != NULL)  // clear list (seal memory leak?)
  199.     {
  200.         current = head;
  201.         head = current->next;
  202.         free(current);
  203.     }
  204.     printList();
  205.     return(EXIT_SUCCESS);
  206. }
Copyright exforsys.com


Here is the complete source code of the above example

Download Sample Game Zip file

This example models 5 people having played a game with their scores added to a list of high scores, then it prints the list. The scores are not entered in any particular order as would happen in real life so the findposition function takes care of sorting the new nodes according to the scores before they are put into the list.

Ads

Here is the output after running the program.

In the next tutorial we will be learning more about Circular Linked Lists and Doubly Linked Lists. Feel free to ask any questions you might have.



 
This tutorial is part of a C Tutorials tutorial series. Read it from the beginning and learn yourself.

C Tutorials

 

Comments