fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. struct ListNode {
  4. int val;
  5. ListNode *next;
  6. ListNode(int x) : val(x), next(NULL) {}
  7. };
  8.  
  9. void insert(ListNode *&head,int value)
  10. {
  11. if(!head)
  12. {
  13. ListNode *&node = head;
  14. node = new ListNode(value); //change head using node..
  15. }
  16. else
  17. {
  18. ListNode *node = head;
  19.  
  20. while(node->next != NULL)
  21. {
  22. node = node->next;
  23. }
  24. node->next = new ListNode(value);
  25. }
  26. }
  27.  
  28. void print(ListNode *head)
  29. {
  30. ListNode *node = head;
  31. for(;node!=NULL;){
  32. printf("%d ",node->val);
  33. node = node->next;
  34. }
  35. }
  36. int main(int argc,char *argv[])
  37. {
  38. ListNode *head = NULL;
  39. insert(head, 5);
  40. insert(head, 1);
  41. insert(head, 2);
  42. insert(head, 3);
  43. print(head);
  44. return 0;
  45. }
  46.  
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
5 1 2 3