Implement a custom linked list with add and iteration functionality.
Write a program to implement custom linked list with minimum functionalities like add and iterations. You can not use in-build functionality of collection framework.
package ztest;
import java.util.Iterator;
public class CustomLinkedList implements Iterable{
private int size = 0;
private Node first;
private Node last;
private static class Node{
Object element;
Node next;
public Node(Object element) {
this.element = element;
}
}
public void add(Object element){
Node newNode = new Node(element);
Node preLast = this.last;
this.last = newNode;
if(this.first == null){
this.first = newNode;
}else{
preLast.next = newNode;
}
size++;
}
private class CustomListIterator implements Iterator{
int cursor;
Node currentNode = first;
@Override
public boolean hasNext() {
return cursor < size;
}
@Override
public Object next() {
Node tempNode = currentNode;
currentNode = currentNode.next;
cursor++;
return tempNode.element;
}
}
@Override
public Iterator iterator() {
return new CustomListIterator();
}
public static void main(String[] args) {
CustomLinkedList customLinkedList = new CustomLinkedList();
customLinkedList.add(1);
customLinkedList.add(4);
customLinkedList.add(6);
for (Object object : customLinkedList) {
System.out.println(object);
}
}
}
Comments
Post a Comment