25.11.2014 Views

Algorithms and Data Structures

Algorithms and Data Structures

Algorithms and Data Structures

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

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

(*input phase*)<br />

NEW(head); tail := head; Texts.Scan(S);<br />

WHILE S.class = Texts.Int DO<br />

x := S.i; Texts.Scan(S); y := S.i; p := find(x); q := find(y);<br />

NEW(t); t.id := q; t.next := p.trail;<br />

p.trail := t; INC(q.count); Texts.Scan(S)<br />

END<br />

head<br />

tail<br />

key<br />

count<br />

1<br />

0<br />

2<br />

1<br />

4<br />

2<br />

6<br />

1<br />

10<br />

2<br />

8<br />

2<br />

3<br />

2<br />

5<br />

2<br />

7<br />

0<br />

9<br />

1<br />

next<br />

trail<br />

id<br />

next<br />

id<br />

next<br />

Fig. 4.15. List structure generated by TopSort program<br />

After the data structure of Fig. 4.15 has been constructed in this input phase, the actual process of<br />

topological sorting can be taken up as described above. But since it consists of repeatedly selecting an<br />

element with a zero count of predecessors, it seems sensible to first gather all such elements in a linked<br />

chain. Since we note that the original chain of leaders will afterwards no longer be needed, the same field<br />

called next may be used again to link the zero predecessor leaders. This operation of replacing one chain<br />

by another chain occurs frequently in list processing. It is expressed in detail here, <strong>and</strong> for reasons of<br />

convenience it constructs the new chain in reverse order.<br />

(*search for leaders without predecessors*)<br />

p := head; head := NIL;<br />

WHILE p # tail DO<br />

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

IF q.count = 0 THEN (*insert q^ in new chain*)<br />

q.next := head; head := q<br />

END<br />

END<br />

Referring to Fig. 4.15, we see that the next chain of leaders is replaced by the one of Fig. 4.16 in which<br />

the pointers not depicted are left unchanged.<br />

1<br />

0<br />

7<br />

0 head<br />

NIL

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

Saved successfully!

Ooh no, something went wrong!