1. Introduction
Counting the occurrence of an integer in a linked list is a fundamental operation that can be useful in various scenarios, such as determining the frequency of a particular value. In this blog post, we will implement a Java program to count the occurrence of a given integer in a linked list.
2. Program Steps
1. Define a Node class to represent each element of the linked list.
2. Implement a LinkedList class to manage the list operations.
3. Within the LinkedList class, add a method named countOccurrence(int searchValue).
– Traverse the list and count the occurrence of searchValue.
4. Test the functionality with a driver method.
3. Code Program
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
Node head;
// Add a new node at the end
public void append(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
return;
}
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
}
// Count occurrence of a given value
public int countOccurrence(int searchValue) {
Node temp = head;
int count = 0;
while (temp != null) {
if (temp.data == searchValue) {
count++;
}
temp = temp.next;
}
return count;
}
// Utility function to print the list
public void printList() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " -> ");
temp = temp.next;
}
System.out.println("NULL");
}
}
public class LinkedListDemo {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.append(5);
list.append(6);
list.append(5);
list.append(3);
list.append(7);
list.append(5);
list.append(9);
System.out.println("Original List:");
list.printList();
int value = 5;
int occurrences = list.countOccurrence(value);
System.out.println("\nOccurrences of " + value + ": " + occurrences);
}
}
Output:
Original List: 5 -> 6 -> 5 -> 3 -> 7 -> 5 -> 9 -> NULL Occurrences of 5: 3
4. Step By Step Explanation
1. The Node class represents an individual element of the linked list. Each node has data and a reference to the next node, next.
2. The LinkedList class provides basic linked list operations. We use the append method to add elements to the end of the list.
3. The countOccurrence method determines how many times a given value appears in the list by:
– Traversing the entire list.
– Incrementing a count whenever the searchValue matches a node's data.
4. In the LinkedListDemo class, we demonstrate this functionality by creating a linked list and then counting the occurrence of the value 5.
By using this approach, we can easily determine how many times a specific value appears in a linked list.