forked from andrei-punko/java-interview-coding
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChainLink.java
More file actions
57 lines (50 loc) · 1.57 KB
/
Copy pathChainLink.java
File metadata and controls
57 lines (50 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package by.andd3dfx.common;
/**
* <pre>
* You are holding one link of a chain in your hand. Implement method longerSide() to find which side of the
* chain, relative to the link you are holding, has more links.
*
* If the left side has more links return LEFT, if the right side has more links return RIGHT,
* and if both sides have an equal number of links or if the chain is a closed loop, return NONE.
*
* For example, for the code below, the output should be RIGHT:
*
* ChainLink left = new ChainLink();
* ChainLink middle = new ChainLink();
* ChainLink right = new ChainLink();
* left.append(middle);
* middle.append(right);
* System.out.println(left.longerSide());
* </pre>
*/
public class ChainLink {
public enum Side {
NONE, LEFT, RIGHT
}
private ChainLink left;
private ChainLink right;
public void append(ChainLink newRightLink) {
if (this.right != null) {
throw new IllegalStateException("Link already connected!");
}
this.right = newRightLink;
newRightLink.left = this;
}
public Side longerSide() {
ChainLink left = this.left;
ChainLink right = this.right;
while (true) {
if (left == right) {
return Side.NONE;
}
if (left == null) {
return Side.RIGHT;
}
if (right == null) {
return Side.LEFT;
}
left = left.left;
right = right.right;
}
}
}