Guest User

Untitled

a guest
Jul 19th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. private void InsertInOrder(CarListEntry e)
  2. {
  3. //create the current and previous object references for the linked list
  4. CarListEntry current = head;
  5. CarListEntry previous = null;
  6.  
  7. //if the entry is empty then return nothing
  8. if (e == null)
  9. {
  10. return;
  11. }
  12.  
  13. //if the list is empty, then have the head aand tail refer to the
  14. //element being added, and it's next reference to be null. Return
  15. //Nothing
  16. if (head == null)
  17. {
  18. head = e;
  19. tail = e;
  20. e.Next = null;
  21. return;
  22. }
  23. //traverse through the list. If the current item is larger than the
  24. //item we are adding (in terms of year) then make the previous item
  25. //refer to the current item and the current refer to the item after it
  26. while(current.Next != null && (current.Data.Year > e.Data.Year))
  27. {
  28. previous = current;
  29. current = current.Next;
  30. }
  31.  
  32. //if the previous items happens to be null, then it is the first
  33. //element. Update it as the head.
  34. if (previous == null)
  35. {
  36. e.Next = head;
  37. head = e;
  38. }
  39.  
  40. else
  41. {
  42. //if the item after the previous is empty then it is the tail
  43. //update the tail in the list.
  44. if (previous.Next == null)
  45. {
  46. tail.Next = e;
  47. tail = e;
  48. }
  49.  
  50. //if it is in the middle, have the item after the previous be
  51. //the updated items new 'next' reference, and have the item
  52. //before it equal the item to be added
  53. e.Next = previous.Next;
  54. previous.Next = e;
  55. }
  56. }
Add Comment
Please, Sign In to add comment