Created
July 31, 2023 16:16
-
-
Save Prajwalprakash3722/0ea9a57db9da11bba413692075183da8 to your computer and use it in GitHub Desktop.
CustomLinkedList.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Iterator; | |
class Node { | |
int value; | |
Node node; | |
} | |
public class Solution { | |
public static void main(String[] args) { | |
Node head = null; | |
Node current = null; | |
// Construct the linked list with 10 nodes | |
for (int i = 0; i < 10; i++) { | |
Node newNode = new Node(); | |
newNode.value = i; | |
if (head == null) { | |
head = newNode; | |
current = head; | |
} else { | |
current.node = newNode; | |
current = newNode; | |
} | |
} | |
Node finalHead = head; | |
// integrating Iterator to my custom Node class, | |
// here Iterator is a interface from java Util, we have to implement the 2 mandatory methods of `hasNext()` & `next()` | |
// only place it helps is to maintain abstract and simple looping similar to looping a array lol :) | |
Iterator<Node> it = new Iterator<Node>() { | |
Node node = finalHead; | |
@Override | |
public boolean hasNext() { | |
return node != null; | |
} | |
@Override | |
public Node next() { | |
Node temp = node; | |
node = node.node; | |
return temp; | |
} | |
}; | |
// Print the linked list using the iterator | |
while (it.hasNext()) { | |
System.out.println(it.next().value); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment