To implement a custom linked list in Java with methods to add elements, display the list, find the nth element from the start, and find the nth element from the end, we can create a simple singly linked list. Below is a complete implementation including all the requested functionalities:
CustomLinkedList.java
public class CustomLinkedList {
private Node head;
// Inner class to represent a node in the linked list
private static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
// Method to add an element to the end of the linked list
public void add(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
}
// Method to display all elements in the linked list
public void display() {
Node current = head;
while (current != null) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.println("null");
}
// Method to find the nth element from the start (1-based index)
public int findNthFromStart(int n) {
Node current = head;
int count = 1;
while (current != null && count < n) {
current = current.next;
count++;
}
if (current != null) {
return current.data;
} else {
throw new IllegalArgumentException("Invalid index: " + n);
}
}
// Method to find the nth element from the end (1-based index)
public int findNthFromEnd(int n) {
Node mainPtr = head;
Node refPtr = head;
int count = 0;
// Move refPtr n nodes ahead
while (count < n) {
if (refPtr == null) {
throw new IllegalArgumentException("Invalid index: " + n);
}
refPtr = refPtr.next;
count++;
}
// Move both pointers until refPtr reaches the end
while (refPtr != null) {
mainPtr = mainPtr.next;
refPtr = refPtr.next;
}
if (mainPtr != null) {
return mainPtr.data;
} else {
throw new IllegalArgumentException("Invalid index: " + n);
}
}
public static void main(String[] args) {
CustomLinkedList list = new CustomLinkedList();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);
list.display(); // Display the list
// Find nth element from start
System.out.println("3rd element from start: " + list.findNthFromStart(3)); // Should print 30
// Find nth element from end
System.out.println("2nd element from end: " + list.findNthFromEnd(2)); // Should print 40
}
}
Post a Comment