Advertisement
yasenst

Printing a linked listed using recursion

Apr 24th, 2017
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.29 KB | None | 0 0
  1. // we can print it both in forward and reversed order by only slightly adjusting the Print function
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. struct Node {
  6.     int data;
  7.     struct Node *next;
  8. };
  9.  
  10. void Print(struct Node* p)
  11. {
  12.     if(p == NULL) return; // duno na rekursiqta
  13.     printf("%d ", p->data); // print the first
  14.     Print(p->next); // recursively call the next one
  15. }
  16.  
  17. struct Node* Insert(struct Node* head, int data)
  18. {
  19.     struct Node* temp = (struct Node*) malloc(sizeof(struct Node)); // create node
  20.     temp->data = data; // store data in newly created node
  21.     temp->next = NULL; // set it to initially point to null
  22.     if(head == NULL) head = temp; // if empty
  23.     else {  // if not empty
  24.         struct Node* temp1 = head; // set new pointer to the start
  25.         while(temp1->next != NULL) temp1 = temp1->next; // go to the last
  26.         temp1->next = temp; // set it to point to the new one
  27.     }
  28.     return head;
  29. }
  30.  
  31. int main()
  32. {
  33.     struct Node* head = NULL;
  34.     head = Insert(head,5);
  35.     head = Insert(head, 8);
  36.     head = Insert(head, 11);
  37.     head = Insert(head, 14);
  38.     Print(head);
  39.  
  40.     return 0;
  41. }
  42.  
  43. // Print in reverse order:
  44. // void Print(struct Node* p)
  45. //{
  46. //  if(p == NULL) return;
  47. //    Print(p->next);
  48. //  printf("%d ", p->data);
  49. // }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement