25.11.2014 Views

Algorithms and Data Structures

Algorithms and Data Structures

Algorithms and Data Structures

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

N.Wirth. <strong>Algorithms</strong> <strong>and</strong> <strong>Data</strong> <strong>Structures</strong>. Oberon version 137<br />

q<br />

8<br />

27<br />

p<br />

13<br />

27 21 13 8 21<br />

Fig. 4.8. Insertion before p^.<br />

The trick evidently consists of actually inserting a new component after p^ <strong>and</strong> thereafter interchanging the<br />

values of the new element <strong>and</strong> p^.<br />

Next, we consider the process of list deletion. Deleting the successor of a p^ is straightforward. This is<br />

shown here in combination with the reinsertion of the deleted element at the head of another list (designated<br />

by q). Figure 4.9 illustrates the situation <strong>and</strong> shows that it constitutes a cyclic exchange of three pointers.<br />

r := p.next; p.next := r.next; r.next := q; q := r<br />

q<br />

q<br />

p<br />

Fig. 4.9. Deletion <strong>and</strong> re-insertion<br />

The removal of a designated element itself (instead of its successor) is more difficult, because we<br />

encounter the same problem as with insertion: tracing backward to the denoted element's predecessor is<br />

impossible. But deleting the successor after moving its value forward is a relatively obvious <strong>and</strong> simple<br />

solution. It can be applied whenever p^ has a successor, i.e., is not the last element on the list. However, it<br />

must be assured that there exist no other variables pointing to the now deleted element.<br />

We now turn to the fundamental operation of list traversal. Let us assume that an operation P(x) has to<br />

be performed for every element of the list whose first element is p^. This task is expressible as follows:<br />

WHILE list designated by p is not empty DO<br />

perform operation P;<br />

proceed to the successor<br />

END<br />

In detail, this operation is described by the following statement:<br />

WHILE p # NIL DO<br />

P(p); p := p.next

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

Saved successfully!

Ooh no, something went wrong!