-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSearchNode.java
82 lines (64 loc) · 1.46 KB
/
SearchNode.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
given head of a SLL and key to be searched, find pos of given key, if given key is absent return -1
ip: 10->5->20->15, x=20
op: 3
ip: 10->15, x=20
op: -1
ip: 3->20->5, x=3
op: 1
in recursive solution, we compare first data item with head's data, if they are matching return 1,
if not, we recusrsively call for remanining LL
now there are two cases:
1) x is present
2) x is absent
*/
class Node {
int data;
Node next;
Node(int x) {
data = x;
next = null;
}
}
public class SearchNode {
public static void main(String[] args) {
Node head = new Node(10);
head.next = new Node(20);
head.next.next = new Node(30);
System.out.println(itrSearch(head, 20));
System.out.println(recSearch(head, 20));
}
public static int itrSearch(Node head, int x)
{
int pos = 1;
Node curr = head;
while (curr != null) {
if (curr.data == x)
return pos;
else {
++pos;
curr = curr.next;
}
}
return -1;
}
public static int recSearch(Node head, int x) {
if (head == null)
return -1;
if(head.data == x)
return 1;
int res = recSearch(head.next, x);
if(res == -1)
return -1;
return (res + 1);
}
}
/*
Time: O(n)
Space:
O(1) or theta(1) for itr
O(n) for recursive
op:
2
2
*/