public class BasicLinkedList<T> implements Iterable<T> {
public int size;
private class Node {
private T data;
private Node next;
private Node(T data) {
this.data = data;
next = null;
}
}
private Node head;
private Node tail;
public BasicLinkedList() {
head = tail = null;
}
//Add, remove method
public Iterator<T> iterator() {
return new Iterator<T>() {
Node current = head;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public T next() {
if(hasNext()){
T data = current.data;
current = current.next;
return data;
}
return null;
}
@Override
public void remove(){
throw new UnsupportedOperationException("Remove not implemented.");
}
};
#Enhances For Loop
for (String temp : linkedList) {
System.out.println(temp);
}
import java.util.LinkedList;
class Main {
public static void main(String[] args) {
// Creating a linked list
LinkedList<String> animals = new LinkedList<>();
animals.add("Cow");
animals.add("Cat");
animals.add("Dog");
System.out.println("LinkedList: " + animals);
// Using forEach loop
System.out.println("Accessing linked list elements:");
for(String animal: animals) {
System.out.print(animal);
System.out.print(", ");
}
}
}