Advertisement
Guest User

Untitled

a guest
Jul 20th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. void printCommon(Node a, Node b) {
  2. Stack<Node> stackA = new Stack<>();
  3. Stack<Node> stackB = new Stack<>();
  4. Node currentA = a;
  5. Node currentB = b;
  6.  
  7. while ((!stackA.isEmpty() || currentA != null) && (!stackB.isEmpty() || currentB != null)) {
  8. if (currentA != null) {
  9. stackA.push(currentA);
  10. currentA = currentA.left;
  11. } else if (currentB != null) {
  12. stackB.push(currentB);
  13. currentB = currentB.left;
  14. } else if (!stackA.isEmpty() && !stackB.isEmpty()) {
  15. currentA = stackA.pop();
  16. currentB = stackB.pop();
  17.  
  18. if (currentA.data == currentB.data) {
  19. System.out.print(currentA.data + " ");
  20. currentA = currentA.right;
  21. currentB = currentB.right;
  22. } else if (currentA.data < currentB.data) {
  23. currentA = currentA.right;
  24. stackB.push(currentB);
  25. currentB = null;
  26. } else if (currentA.data > currentB.data) {
  27. currentB = currentB.right;
  28. stackA.push(currentA);
  29. currentA = null;
  30. }
  31. }
  32. }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement