Data Structures and Algorithms with Object-Oriented Design Patterns in C#
next up previous contents index

Prepend Method

To prepend  an element to a linked list is to insert that element in front of the first element of the list. The prepended list element becomes the new head of the list. Program gif gives the algorithm for the Prepend method of the LinkedList class.

   program3811
Program: LinkedList class Prepend method.

The Prepend method first creates a new LinkedList.Element. Its datum field is initialized with the value to be prepended to the list, item; and the next field refers to the first element of the existing list by initializing it with the current value of head. If the list is initially empty, both head and tail refer to the new element. Otherwise, just head needs to be updated.

Note, the new operator initializes the new LinkedList.Element instance by calling its constructor. In Section gif the running time of the constructor was determined to be O(1). And since the body of the Prepend method adds only a constant amount of work, the running time of the Prepend method is also O(1).


next up previous contents index

Bruno Copyright © 2001 by Bruno R. Preiss, P.Eng. All rights reserved.