Amazon Interview Question
SDE-2sCountry: United States
Interview Type: Phone Interview
public class UDLinkedList {
private Node head;
public UDLinkedList(Node node) {
head = node;
}
public static void main(String[] args) {
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.down = new Node(6);
head.down.next = new Node(7);
head.down.next.next = new Node(10);
head.down.next.down = new Node(8);
head.down.next.down.next = new Node(9);
head.down.next.next.down = new Node(11);
head.down.next.next.down.next = new Node(12);
UDLinkedList list = new UDLinkedList(head);
UDLLIterator iterator = list.iterator();
try {
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (Exception e) {
e.printStackTrace();
}
}
public UDLLIterator iterator() {
return new UDLLIterator();
}
private static class Node {
private int value;
private Node next;
private Node down;
public Node(int v) {
this.value = v;
}
}
private class UDLLIterator {
private Stack<Node> stack;
public UDLLIterator() {
stack = new Stack<>();
stack.push(head);
}
public boolean hasNext() {
return !stack.isEmpty();
}
public int next() throws Exception {
if (hasNext()) {
Node current = stack.pop();
if (current.next != null) {
stack.push(current.next);
}
if (current.down != null) {
stack.push(current.down);
}
return current.value;
} else {
throw new Exception("No element to iterate over");
}
}
}
}
Can you please give the explanation of this question clearly
- Anonymous September 02, 2015