Advertisement
Guest User

Untitled

a guest
Dec 16th, 2018
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<cs50.h>
  3. #include<stdlib.h>
  4.  
  5.  
  6.  
  7. struct linkedList
  8. {
  9. int data;
  10. struct linkedList *next;
  11. };
  12.  
  13. typedef struct linkedList *node; //define node as pointer of data type struct LinkedList
  14.  
  15. node createNode() // returns type node, name of function is createNode, takes 0 arguments
  16. {
  17. node temp; //declare a node
  18. temp = (node)malloc(sizeof(struct linkedList)); //allocate memory using malloc
  19. temp -> next = NULL; //make next point to NULL
  20. return temp; //return the new node
  21. }
  22.  
  23. node addNode (node head, int value)
  24. {
  25. node temp, p; //declare two nodes temp and p
  26. temp = createNode();//createNode will return a new node with data = value and next pointing to NULL
  27. temp -> data = value; //add element's value to data part of node
  28. if (head == NULL)
  29. {
  30. head = temp; // when linked list is empty
  31. }
  32. else
  33. {
  34. p = head; // assign head to p
  35. while (p->next != NULL)
  36. {
  37. p = p->next; // taverse the list until p is the last node. The last node always points to NULL.
  38. }
  39. p -> next = temp; //point the previous last node to the node created
  40.  
  41.  
  42. }
  43. return head;
  44.  
  45. }
  46.  
  47. int main (void)
  48. {
  49. //creates first node
  50. node new = createNode();
  51.  
  52. //adds a node with the value 6
  53. addNode(new, 6);
  54.  
  55. //add some more nodes
  56. for (int i=0; i<5; i++)
  57. {
  58. addNode(new, i);
  59. }
  60. //traverse the list
  61.  
  62. node p;
  63. p = new;
  64. while (p != NULL)
  65. {
  66. p = p -> next;
  67. printf("%i\n", new ->data);
  68. }
  69.  
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement