Amazon Interview Question
SDE-3sCountry: United States
Interview Type: In-Person
public static Node pointToNextHigherElement(Node head) {
Stack<Node> stack = new Stack<Node>();
Node current = head;
stack.push(current);
current = current.next;
while ( current != null){
Node elementFromStack = stack.pop();
if (elementFromStack.value > current.value) {
stack.push(elementFromStack);
stack.push(current);
} else {
stack.push(current);
stack.push(elementFromStack);
}
current = current.next;
}
while(!stack.isEmpty()) {
Node temp = stack.pop();
if (!stack.isEmpty()) {
Node next = stack.peek();
temp.random = next;
}
}
return head;
}
- Trutgeek September 06, 2017