Question:
Problem statement
You have been given a singly linked list of integers. Write a function that returns the index/position of integer data denoted by 'N' (if it exists). Return -1 otherwise.
Note :/****************************************************************
Following is the class structure of the Node class:
class Node<T> {
T data;
Node<T> next;
public Node(T data) {
this.data = data;
}
}
*****************************************************************/
public class Solution {
public static int findNode(Node<Integer> head, int n) {
// Write your code here.
if(head == null){
return -1;
}
Node<Integer> temp = head;
int count =0;
while(temp != null){
if(temp.data == n){
return count;
}
temp = temp.next;
count++;
}
return -1;
}
}
1) why we are using temp variable ?
Ans: if we need to return node then only on that case we need to use temp variable ,
maan lo ham ek linkedlist me se remove kar rhe element to us case me agar ham temp use
nhi karenge to head ka address lost ho jayega aur aise me use return krna hamare liye
mushkil ho jayega isliye ham use karte hai , here we can solve this without temp.
2) why we are checking if(temp.data == n) ?
Ans: agar ham temp.data ke bajaye sirf temp == n likhenge to wo equalities nhi hogi
means n ek int type ka data hai jab ki temp ek node hai isliye temp == n nhi ho skta
hai, we can do one thing we can create like temp.data == n.
Comments
Post a Comment