Untitled
class ListNode { int val; ListNode next; ListNode(int val) { this.val = val; this.next = null; } } public class LinkedListOperations { // Convert Array to Linked List public ListNode arrayToLinkedList(int[] arr) { if (arr == null || arr.length == 0) return null; ListNode head = new ListNode(arr[0]); ListNode current = head; for (int i = 1; i < arr.length; i++) { current.next = new ListNode(arr[i]); current = current.next; } return head; } // Count Nodes in Linked List public int countNodes(ListNode head) { int count = 0; ListNode current = head; while (current != null) { count++; current = current.next; } return count; } // Search in Linked List public boolean searchInLinkedList(ListNode head, int target) { ListNode current = head; while (current != null) { if (current.val == target) { return true; // Value found } current = current.next; } return false; // Value not found } // Helper Method: Print Linked List public void printLinkedList(ListNode head) { ListNode current = head; while (current != null) { System.out.print(current.val + " -> "); current = current.next; } System.out.println("null"); } // Main Method: Test All Operations public static void main(String[] args) { LinkedListOperations operations = new LinkedListOperations(); // Convert Array to Linked List int[] arr = {10, 20, 30, 40, 50}; ListNode head = operations.arrayToLinkedList(arr); // Print Linked List System.out.print("Linked List: "); operations.printLinkedList(head); // Count Nodes int nodeCount =
Leave a Comment