diff --git a/BucketChain/Person.cs b/BucketChain/Person.cs index c94cdfc..4a047c0 100644 --- a/BucketChain/Person.cs +++ b/BucketChain/Person.cs @@ -50,24 +50,36 @@ public sealed class Person /// neighbor of this person; otherwise it will become the right hand side neighbor public void JoinChain(Person neighbor, bool isLeftNeighbor) { - // expect that that all neighbors of the new person are null - // so that way we truly know that the provided person is new - if (neighbor.LeftNeighbor == null || neighbor.RightNeighbor == null) + var neighborOfNeighbor = isLeftNeighbor ? neighbor.RightNeighbor : neighbor.LeftNeighbor; + if (neighborOfNeighbor != null) { - return; - } - - var thisNeighbor = isLeftNeighbor ? LeftNeighbor : RightNeighbor; - thisNeighbor?.JoinChain(neighbor, isLeftNeighbor); - if (isLeftNeighbor) - { - neighbor.RightNeighbor = this; - LeftNeighbor = neighbor; + if(isLeftNeighbor) + { + neighborOfNeighbor.LeftNeighbor = this; + RightNeighbor = neighborOfNeighbor; + LeftNeighbor = neighbor; + neighbor.RightNeighbor = this; + } + else + { + neighborOfNeighbor.RightNeighbor = this; + LeftNeighbor = neighborOfNeighbor; + RightNeighbor = neighbor; + neighbor.LeftNeighbor = this; + } } else { - neighbor.LeftNeighbor = this; - RightNeighbor = neighbor; + if (isLeftNeighbor) + { + neighbor.RightNeighbor = this; + LeftNeighbor = neighbor; + } + else + { + neighbor.LeftNeighbor = this; + RightNeighbor = neighbor; + } } }