Linked List in Java
In Java, a linked list can be implemented using the LinkedList
class which is part of the Java Collections framework. Here's an example:
import java.util.LinkedList;
public class MyLinkedList {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<String>();
// Adding elements to the linked list
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
// Printing elements of the linked list
System.out.println("Elements of the linked list are: " + list);
// Adding an element at a specific position
list.add(2, "F");
// Removing an element from the linked list
list.remove("E");
// Printing elements of the modified linked list
System.out.println("Modified elements of the linked list are: " + list);
// Accessing an element from the linked list
String element = list.get(3);
System.out.println("Element at index 3 is: " + element);
}
}
In this example, we first create a new LinkedList
object and add some elements to it using the add()
method. We then print the contents of the linked list using the toString()
method.
Next, we add an element "F" at position 2 and remove the element "E" from the linked list. We then print the modified linked list.
Finally, we access the element at index 3 using the get()
method and print it to the console.
Note that the LinkedList
class provides many other useful methods for working with linked lists, such as addFirst()
, addLast()
, removeFirst()
, removeLast()
, indexOf()
, lastIndexOf()
, and many more.
Comments
Post a Comment