In: Computer Science
Find a node in a LinkedList In Java:
1. (2 pts) Define the nodes in the LinkedList.
2. (2 pts) Create the LinkedList using the ListNode class.
3. (4 pts) 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.
4. (2 pts) 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
Java code
import java.util.Scanner;
class ListNode{
int data;
ListNode next;
public ListNode(int val) {
data = val;
next = null;
}
public int getData() {
return data;
}
public void setData(int val) {
data = val;
}
public ListNode getNext() {
return next;
}
public void setNext(ListNode next) {
this.next = next;
}
}
public class Main {
public static void main(String args[]) {
Scanner scan = new
Scanner(System.in);
int n,num;
System.out.print("Enter number of
node in LinkedList: ");
n = scan.nextInt();
System.out.println("Enter elements
in Linked list");
ListNode root = null;
ListNode tail = null;
for(int i=0;i<n;i++) {
System.out.print("Enter value: ");
num =
scan.nextInt();
ListNode newNode
= new ListNode(num);
if(root == null)
{
root = newNode;
tail = root;
}
else {
tail.setNext(newNode);
tail = newNode;
}
}
System.out.print("Enter value to
search: ");
num = scan.nextInt();
System.out.println(search(root ,
num));
}
public static Integer search(ListNode root, int
num) {
while(root != null) {
if(root.getData() == num) return num;
root =
root.getNext();
}
return null;
}
}