Advertisement
Robert_JR

Singly Linked List (Append)

Feb 11th, 2018
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.09 KB | None | 0 0
  1. /*
  2.     Singly Linked List
  3.     Illustration of append() function
  4.     By Rijoanul Hasan Shanto
  5.     Reference: www.shafaetsplanet.com/planetcoding/?p=763
  6. */
  7.  
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. struct Node
  11. {
  12.     int data;
  13.     struct Node *next;
  14. };
  15.  
  16. typedef struct Node node;
  17.  
  18. node *head = 0;
  19.  
  20. void append(int data)
  21. {
  22.     if(head == 0)
  23.     {
  24.         head = (node*) malloc(sizeof (node));
  25.  
  26.         head->data = data;
  27.         head->next = 0;
  28.     }
  29.     else
  30.     {
  31.         node *temp = head;
  32.  
  33.         while(temp->next != 0)
  34.         {
  35.             temp = temp->next;
  36.         }
  37.  
  38.         node *newNode = (node*) malloc(sizeof (node));
  39.  
  40.         newNode->data = data;
  41.         newNode->next = 0;
  42.  
  43.         temp->next = newNode;
  44.     }
  45. }
  46.  
  47. void display()
  48. {
  49.     node *temp = (node*) malloc(sizeof (node));
  50.     temp = head;
  51.  
  52.     while(temp->next != 0)
  53.     {
  54.         printf("%d\n", temp->data);
  55.         temp = temp->next;
  56.     }
  57.     printf("%d\n", temp->data);
  58. }
  59.  
  60. int main()
  61. {
  62.     int i;
  63.     for(i = 0; i < 5; i++)
  64.     {
  65.         append(i+2);
  66.     }
  67.  
  68.     display();
  69.  
  70.     return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement