In: Computer Science
1. (10 pts) Define the nodes in the LinkedList. Create the LinkedList using the ListNode class. Create a method to find a node with given value in a LinkedList. Return the value is this value exists in the LinkedList. Return null if not exists. Use these two examples to test your method.
Example 1:
Input: 1 -> 2 -> 3, and target value = 3
Output: 3
Example 2:
Input: 1 -> 2 -> 3, and target value = 4
Output: null
Using Eclipse for Java
/*If you any query do comment in the comment section else like the solution*/
class ListNode
{
Node head;
class Node
{
int val;
Node link;
Node(int d) {
val = d; link = null;
}
}
public void push(int val)
{
Node newNode = new Node(val);
newNode.link = head;
head = newNode;
}
int searchByTarget(int target) {
Node ptr = head;
while(ptr != null) {
if(ptr.val == target) {
return target;
}
ptr = ptr.link;
}
return 0;
}
public static void main(String args[])
{
ListNode llist = new ListNode();
llist.push(1);
llist.push(2);
llist.push(3);
int target = 4;
int res = llist.searchByTarget(target);
if(res != 0)
System.out.println(res);
else
System.out.println("null");
}
}