Advertisement
Guest User

Untitled

a guest
Sep 21st, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. import java.util.Arrays;
  2. import java.util.Stack;
  3.  
  4. public class NextLargerNode {
  5.  
  6. static class Node {
  7. int value;
  8. Node next;
  9. public Node(int value) {
  10. this.value = value;
  11. this.next = null;
  12. }
  13. }
  14. int [] result;
  15. public void nextGreaterNodes(Node head) {
  16. System.out.print("Linked List: ");
  17. Stack<Integer> stack = new Stack<>();
  18. nextGreaterNodeUtil(head, 0, stack);
  19. System.out.println();
  20. System.out.println("Greater Array: " + Arrays.toString(result));
  21. }
  22.  
  23. void nextGreaterNodeUtil(Node node, int index, Stack<Integer> stack) {
  24. if (node == null) {
  25. result = new int[index];
  26. return;
  27. }
  28.  
  29. //recursive call
  30. System.out.print("->"+node.value);
  31. nextGreaterNodeUtil(node.next, index + 1, stack);
  32.  
  33. //tail recursion, will move from right to left
  34. int current = node.value;
  35. while (!stack.isEmpty() && stack.peek() < current)
  36. stack.pop();
  37.  
  38. int greater = (stack.isEmpty() == false) ? stack.peek() : 0;
  39. result[index] = greater;
  40. stack.push(current);
  41. }
  42.  
  43. public static void main(String[] args) {
  44. Node head = new Node(6);
  45. head.next = new Node(2);
  46. head.next.next = new Node(4);
  47. head.next.next.next = new Node(3);
  48. head.next.next.next.next = new Node(5);
  49. head.next.next.next.next.next = new Node(10);
  50. head.next.next.next.next.next.next = new Node(6);
  51.  
  52. NextLargerNode n = new NextLargerNode();
  53. n.nextGreaterNodes(head);
  54.  
  55. }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement