Пример #1
0
    public List <uint> CrabGameCustomLinkedList(List <uint> numbers, ulong numMoves)
    {
        LL  cups           = new LL(numbers);
        var currentNode    = cups.Head;
        var smallestNumber = numbers.Min();

        for (ulong move = 0; move < numMoves; move++)
        {
            // remove the following 3 values after the current node.
            var pickupNodes = new List <LLNode <uint> >(3);
            for (int i = 0; i < 3; ++i)
            {
                // remove head
                if (currentNode.Next == null)
                {
                    pickupNodes.Add(cups.RemoveHead());
                }
                else
                {
                    pickupNodes.Add(cups.RemoveNext(currentNode));
                }
            }

            // find the destination node, nearest smallest node from the current value.
            LLNode <uint> destinationNode = null;
            for (uint destinationValue = currentNode.Value - 1; destinationValue >= smallestNumber; destinationValue--)
            {
                var lookupNode = cups.Lookup[(int)destinationValue];
                if (lookupNode != null)
                {
                    destinationNode = lookupNode;
                    break;
                }
            }

            // if the above algorithm does not find a value, select the greatest value.
            destinationNode ??= cups.Lookup.Last(x => x != null);

            // Add the nodes after the destination node.
            for (int i = 0; i < 3; i++)
            {
                var nodeToAdd = pickupNodes[i];
                cups.AddAfterNode(destinationNode, nodeToAdd);
                destinationNode = nodeToAdd;
            }
            currentNode = currentNode.Next ?? cups.Head;
        }

        // create a list of values from the linkedlist, with the retained order.
        var node   = cups.Head;
        var result = new List <uint>();

        do
        {
            result.Add(node.Value);
            node = node.Next;
        }while (node != null);
        return(result);
    }