Skip to content

Instantly share code, notes, and snippets.

@Prajwalprakash3722
Created July 31, 2023 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Prajwalprakash3722/0ea9a57db9da11bba413692075183da8 to your computer and use it in GitHub Desktop.
Save Prajwalprakash3722/0ea9a57db9da11bba413692075183da8 to your computer and use it in GitHub Desktop.
CustomLinkedList.java
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