How to Compare Two Nodes in a Linked List Java
In Java, a linked list is a fundamental data structure that consists of nodes, where each node contains data and a reference to the next node. Comparing two nodes in a linked list can be a common task in various scenarios, such as searching for a specific element or merging two linked lists. This article will guide you through the process of comparing two nodes in a linked list using Java.
Firstly, let’s define the Node class, which represents each element in the linked list:
“`java
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
“`
Now, let’s create a method to compare two nodes in the linked list:
“`java
public class LinkedList {
Node head;
public boolean compareNodes(Node node1, Node node2) {
if (node1 == null && node2 == null) {
return true;
}
if (node1 == null || node2 == null) {
return false;
}
return node1.data == node2.data;
}
}
“`
In the `compareNodes` method, we first check if both nodes are null. If they are, we return `true` because two null nodes are considered equal. If either of the nodes is null, we return `false` because one node cannot be equal to a null node. Finally, we compare the data of both nodes and return `true` if they are equal, and `false` otherwise.
To use this method, you can create a linked list and compare two nodes as follows:
“`java
public class Main {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.head = new Node(1);
list.head.next = new Node(2);
list.head.next.next = new Node(3);
Node node1 = list.head.next;
Node node2 = list.head.next.next;
boolean result = list.compareNodes(node1, node2);
System.out.println(“The two nodes are equal: ” + result);
}
}
“`
In this example, we create a linked list with three nodes and compare the second and third nodes. The output will be:
“`
The two nodes are equal: true
“`
This demonstrates that the `compareNodes` method works correctly and can be used to compare any two nodes in a linked list.