fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. class Node {
  5. public:
  6. int val;
  7. Node* next;
  8. Node(int v) {
  9. val = v;
  10. next = nullptr;
  11. }
  12.  
  13. void insert(int v) {
  14. Node* nw = new Node(v);
  15. Node* t = this;
  16. while (t->next != nullptr) {
  17. t = t->next;
  18. }
  19. t->next = nw;
  20. }
  21.  
  22. int search(int s) {
  23. int ans = -1, i = 0;
  24. Node* t = this->next;
  25. while (t->next != nullptr) {
  26. // Debug Purposes
  27. // cerr << t->val << " " << i << " " << s << "\n";
  28. if(t->val == s) break;
  29. t = t->next;
  30. i++;
  31. }
  32. if(t->val == s) ans = i;
  33. return ans;
  34. }
  35.  
  36.  
  37. void print() {
  38. Node* t = next;
  39. while(t->next != nullptr) {
  40. cout << t->val << " ";
  41. t = t->next;
  42. }
  43. cout << t->val << "\n";
  44. }
  45. };
  46.  
  47. int main() {
  48. int t; cin >> t;
  49. while(t--) {
  50. Node *n = new Node(0);
  51. int x = 0;
  52. while(1) {
  53. cin >> x;
  54. if(x == -1) break;
  55. n->insert(x);
  56. }
  57. int q; cin >> q;
  58. cout << n->search(q) << "\n";
  59. }
  60. }
Success #stdin #stdout 0.01s 5324KB
stdin
4
1 2 3 4 5 -1
3
1 2 3 -1
5
1 -1
1
10 20 -1
20
stdout
2
-1
0
1