| 38 | } |
| 39 | |
| 40 | public static BiNode convertToCircular(BiNode root) { |
| 41 | if (root == null) { |
| 42 | return null; |
| 43 | } |
| 44 | |
| 45 | BiNode part1 = convertToCircular(root.node1); |
| 46 | BiNode part3 = convertToCircular(root.node2); |
| 47 | |
| 48 | if (part1 == null && part3 == null) { |
| 49 | root.node1 = root; |
| 50 | root.node2 = root; |
| 51 | return root; |
| 52 | } |
| 53 | BiNode tail3 = part3 == null ? null : part3.node1; |
| 54 | |
| 55 | /* join left to root */ |
| 56 | if (part1 == null) { |
| 57 | concat(part3.node1, root); |
| 58 | } else { |
| 59 | concat(part1.node1, root); |
| 60 | } |
| 61 | |
| 62 | /* join right to root */ |
| 63 | if (part3 == null) { |
| 64 | concat(root, part1); |
| 65 | } else { |
| 66 | concat(root, part3); |
| 67 | } |
| 68 | |
| 69 | /* join right to left */ |
| 70 | if (part1 != null && part3 != null) { |
| 71 | concat(tail3, part1); |
| 72 | } |
| 73 | |
| 74 | return part1 == null ? root : part1; |
| 75 | } |
| 76 | |
| 77 | public static BiNode convert(BiNode root) { |
| 78 | BiNode head = convertToCircular(root); |