Data Structures and Algorithms
with Object-Oriented Design Patterns in C# |
Consider the methods InsertAfter and InsertBefore of the LinkedList.Element class shown in Program . Both methods take a single argument that specifies an item to be inserted into the list. The given item is inserted either in front of or immediately following this list element.
Program: LinkedList.Element class InsertAfter and InsertBefore methods.
The InsertAfter method is almost identical to Append. Whereas Append inserts an item after the tail, InsertAfter inserts an item after an arbitrary list element. Nevertheless, the running time of InsertAfter is identical to that of Append, i.e., it is O(1).
To insert a new item before a given list element, it is necessary to traverse the linked list starting from the head to locate the list element that precedes the given list element. In the worst case, the given element is the at the tail of the list and the entire list needs to be traversed. Therefore, the running time of the InsertBefore method is O(n).