Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private void InsertInOrder(CarListEntry e)
- {
- //create the current and previous object references for the linked list
- CarListEntry current = head;
- CarListEntry previous = null;
- //if the entry is empty then return nothing
- if (e == null)
- {
- return;
- }
- //if the list is empty, then have the head aand tail refer to the
- //element being added, and it's next reference to be null. Return
- //Nothing
- if (head == null)
- {
- head = e;
- tail = e;
- e.Next = null;
- return;
- }
- //traverse through the list. If the current item is larger than the
- //item we are adding (in terms of year) then make the previous item
- //refer to the current item and the current refer to the item after it
- while(current.Next != null && (current.Data.Year > e.Data.Year))
- {
- previous = current;
- current = current.Next;
- }
- //if the previous items happens to be null, then it is the first
- //element. Update it as the head.
- if (previous == null)
- {
- e.Next = head;
- head = e;
- }
- else
- {
- //if the item after the previous is empty then it is the tail
- //update the tail in the list.
- if (previous.Next == null)
- {
- tail.Next = e;
- tail = e;
- }
- //if it is in the middle, have the item after the previous be
- //the updated items new 'next' reference, and have the item
- //before it equal the item to be added
- e.Next = previous.Next;
- previous.Next = e;
- }
- }
Add Comment
Please, Sign In to add comment