Example #1
0
        // Add a new Drug in order based on a user-supplied comparison method.
        // The new Drug goes just before the first one which tests greater than it.
        public void InsertInOrder(Drug data)
        {
            //These new variables are duplicates of the head
            //and of the data
            Node sortedList = new Node(data);
            Node current    = head;
            Node previous   = current;

            //if the head is null, that means that there is only one value in the
            //list, so both head and tail equal to the data.
            if (head == null)
            {
                head = sortedList;
                tail = sortedList;
            }
            //if the head isn't null, you compare the head with the data
            //if the head is bigger then you replace the head with the data
            //and the initial head becomes the second element in the list
            else if (head.CompareTo(sortedList) == 1)
            {
                sortedList.Next = head;
                head            = sortedList;
            }
            //if the head is smaller, then you append the data (put it in the end)
            //and you decrement the list.
            else if (tail.CompareTo(sortedList) == -1)
            {
                Append(data);
                count--;
            }
            //now if we have a list of data, we keep on repeating the same
            //procedure till the last value
            else
            {
                while (current != null)
                {
                    if (current.CompareTo(sortedList) == 1)
                    {
                        sortedList.Next = current;
                        previous.Next   = sortedList;
                        break;
                    }
                    previous = current;
                    current  = current.Next;
                }
            }
            count++;
        }