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.

106 Chap. 4 Lists, Stacks, <strong>and</strong> Queuescurr... 23 12 ...Insert 10: 10curr(a)... 23 12 ...3101 2Figure 4.9 The linked list insertion process. (a) The linked list before insertion.(b) The linked list after insertion. 1 marks the element field of the new linknode. 2 marks the next field of the new link node, which is set to point to wh<strong>at</strong>used to be the current node (the node with value 12). 3 marks the next field ofthe node preceding the current position. It used to point to the node containing 12;now it points to the new node containing 10.Oper<strong>at</strong>or new cre<strong>at</strong>es the new link node <strong>and</strong> calls the Link class constructor, whichtakes two parameters. The first is the element. The second is the value to be placedin the list node’s next field, in this case “curr.next.” Method setNext doesthe assignment to curr’s next field. Figure 4.9 illustr<strong>at</strong>es this three-step process.Once the new node is added, tail is pushed forward if the new element was addedto the end of the list. Insertion requires Θ(1) time.Removing a node from the linked list requires only th<strong>at</strong> the appropri<strong>at</strong>e pointerbe redirected around the node to be deleted. The following lines from the removemethod of Figure 4.8 do precisely this.E it = curr.next().element(); // Remember valuecurr.setNext(curr.next().next()); // Remove from listMemory for the link will eventually be reclaimed by the garbage collector. Figure4.10 illustr<strong>at</strong>es the remove method. Removing an element requires Θ(1) time.Method next simply moves curr one position toward the tail of the list,which takes Θ(1) time. Method prev moves curr one position toward the headof the list, but its implement<strong>at</strong>ion is more difficult. In a singly linked list, there isno pointer to the previous node. Thus, the only altern<strong>at</strong>ive is to march down the listfrom the beginning until we reach the current node (being sure always to remember(b)

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

Saved successfully!

Ooh no, something went wrong!