fork(2) download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct Node
  5. {
  6. int value;
  7. Node *next;
  8. };
  9.  
  10. int find(Node* head, int n) {
  11. if (!head) {
  12. return -1;
  13. }
  14. if (head->value == n) {
  15. return 0;
  16. }
  17. int result = find(head->next, n);
  18. return (result == -1) ? result : 1 + result;
  19. }
  20.  
  21.  
  22. int main()
  23. {
  24. Node *list = new Node{1, new Node{2, new Node{3, nullptr}}};
  25.  
  26. cout << find(list, 1) << endl;
  27. cout << find(list, 2) << endl;
  28. cout << find(list, 3) << endl;
  29. cout << find(list, 4) << endl;
  30.  
  31. return 0;
  32. }
Success #stdin #stdout 0s 4508KB
stdin
Standard input is empty
stdout
0
1
2
-1