11.07.2015 Views

Data Structures and Algorithm Analysis - Computer Science at ...

Data Structures and Algorithm Analysis - Computer Science at ...

Data Structures and Algorithm Analysis - Computer Science at ...

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Sec. 4.1 Lists 103headcurrtailhead20 23 12 15curr(a)tail20 23 10 12(b)15Figure 4.6 Insertion using a header node, with curr pointing one node head ofthe current element. (a) Linked list before insertion. The current node contains 12.(b) Linked list after inserting the node containing 10.currtailheadFigure 4.7 Initial st<strong>at</strong>e of a linked list when using a header node.node like any other, but its value is ignored <strong>and</strong> it is not considered to be an actualelement of the list. The header node saves coding effort because we no longer needto consider special cases for empty lists or when the current position is <strong>at</strong> one endof the list. The cost of this simplific<strong>at</strong>ion is the space for the header node. However,there are space savings due to smaller code size, because st<strong>at</strong>ements to h<strong>and</strong>le thespecial cases are omitted. In practice, this reduction in code size typically savesmore space than th<strong>at</strong> required for the header node, depending on the number oflists cre<strong>at</strong>ed. Figure 4.7 shows the st<strong>at</strong>e of an initialized or empty list when using aheader node.Figure 4.8 shows the definition for the linked list class, named LList. ClassLList inherits from the abstract list class <strong>and</strong> thus must implement all of ClassList’s member functions.Implement<strong>at</strong>ions for most member functions of the list class are straightforward.However, insert <strong>and</strong> remove should be studied carefully.Inserting a new element is a three-step process. First, the new list node iscre<strong>at</strong>ed <strong>and</strong> the new element is stored into it. Second, the next field of the newlist node is assigned to point to the current node (the one after the node th<strong>at</strong> currpoints to). Third, the next field of node pointed to by curr is assigned to point tothe newly inserted node. The following line in the insert method of Figure 4.8does all three of these steps.curr.setNext(new Link(it, curr.next()));

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!