12.07.2015 Views

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

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

110 Chap. 4 Lists, Stacks, <strong>and</strong> Queuesheadcurrtailhead20 23 12 15curr(a)tail20 23 10 12(b)15Figure 4.7 Insertion using a header node, with curr pointing one node head ofthe current element. (a) Linked list before insertion. The current node contains12. (b) Linked list after inserting the node containing 10.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.Implementation for most member functions of the list class is 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 iscreated <strong>and</strong> the new element is s<strong>to</strong>red in<strong>to</strong> it. Second, the next field of the newlist node is assigned <strong>to</strong> point <strong>to</strong> the current node (the one (after) the node that currpoints <strong>to</strong>). Third, the next field of node pointed <strong>to</strong> by curr is assigned <strong>to</strong> point <strong>to</strong>the newly inserted node. The following line in the insert method of Figure 4.8actually does all three of these steps.curr.setNext(new Link(it, curr.next()));Opera<strong>to</strong>r new creates the new link node <strong>and</strong> calls the construc<strong>to</strong>r for the Linkclass, which takes two parameters. The first is the element. The second is the value<strong>to</strong> be placed in the list node’s next field, in this case “curr.next.” Figure 4.9illustrates this three-step process. Once the new node is added, tail is pushedforward if the new element was added <strong>to</strong> the end of the list. Insertion requires Θ(1)time.Removing a node from the linked list requires only that the appropriate pointerbe redirected around the node <strong>to</strong> be deleted. This memory will eventually bereclaimed by the garbage collec<strong>to</strong>r. The following lines from the remove methodof Figure 4.8 do precisely this.E it = curr.next().element(); // Remember valuecurr.setNext(curr.next().next()); // Remove from list

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

Saved successfully!

Ooh no, something went wrong!