-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFind a Node in LinkedList
59 lines (47 loc) · 1.18 KB
/
Find a Node in LinkedList
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
import java.util.*;
public class Solution{
class Node{
int data;
Node next;
public Node(int data){
this.data = data;
this.next = null;
}
}
static Node head = null;
static Node tail = null;
public void add(int data){
Node newNode = new Node(data);
if(head == null){
head = newNode;
tail = newNode;
} else{
tail.next = newNode;
tail = newNode;
}
}
public static int search(Node head , int x){
Node temp = head;
int count = 0;
while(temp != null){
if(temp.data == x){
return count;
}
count++;
temp = temp.next;
}
return -1;
}
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Solution l1 = new Solution();
while(n != -1){
l1.add(n);
n = sc.nextInt();
}
int x = sc.nextInt();
int ans = search(head , x);
System.out.println(ans);
}
}