Advertisement
Guest User

Untitled

a guest
Nov 21st, 2019
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.06 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3.  
  4. struct node
  5. {
  6. int data;
  7. struct node *next;
  8. };
  9. typedef struct node *list;
  10.  
  11. list insert (list l, int data); //insert function adds a new node at the beginning of the list
  12. void printL(list l); //prints the values of the list
  13.  
  14. int main()
  15. {
  16. list l = NULL;
  17. insert(l,8);
  18. insert(l,9);
  19. printL (l);
  20. }
  21.  
  22. list insert(list l, int data)
  23. {
  24. int k=0;
  25. list p; //node that is going to be inserted
  26. list cur=l;
  27.  
  28. //counts how many nodes are in the list
  29. while(cur!=NULL)
  30. {
  31. cur=cur->next;
  32. k++;
  33.  
  34. }
  35. if (k=5) //if there are 5 nodes the list is full and no more nodes can be added
  36. {
  37. printf("list is full!\n");
  38. return l;
  39. }
  40. else //else add the node at the beginning
  41. {
  42. p=malloc(sizeof(list));
  43. p->data=data;
  44. p->next=l;
  45. l=p;
  46. printf("%d has been inserted\n", data);
  47. return l;
  48. }
  49. }
  50.  
  51. void printL(list l)
  52. {
  53. if(l==NULL)
  54. {
  55. printf("END\n"); //if the list is empty print END
  56. }
  57. else
  58. {
  59. printf("%d ->", l->data);
  60. printL(l->next);
  61. }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement