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 158<br />

1. A word is considered as any sequence of letters <strong>and</strong> digits starting with a letter.<br />

2. Since words may be of widely different lengths, the actual characters are stored in an array buffer, <strong>and</strong><br />

the tree nodes contain the index of the key's first character.<br />

3. It is desirable that the line numbers be printed in ascending order in the cross-reference index.<br />

Therefore, the item lists must be generated in the same order as they are scanned upon printing. This<br />

requirement suggests the use of two pointers in each word node, one referring to the first, <strong>and</strong> one referring<br />

to the last item on the list. We assume the existence of global writer W, <strong>and</strong> a variable representing the<br />

current line number in the text.<br />

CONST WordLen = 32; (* ADenS443_CrossRef *)<br />

TYPE Word = ARRAY WordLen OF CHAR;<br />

Item = POINTER TO RECORD)<br />

lno: INTEGER; next: Item<br />

END;<br />

Node = POINTER TO RECORD<br />

key: Word;<br />

first, last: Item; (*list*)<br />

left, right: Node (*tree*)<br />

END;<br />

VAR line: INTEGER;<br />

PROCEDURE search (VAR w: Node; VAR a: Word);<br />

VAR q: Item;<br />

BEGIN<br />

IF w = NIL THEN (*word not in tree; new entry, insert*)<br />

NEW(w); NEW(q); q.lno := line;<br />

COPY(a, w.key); w.first := q; w.last := q; w.left := NIL; w.right := NIL<br />

ELSIF w.key < a THEN search(w.right, a)<br />

ELSIF w.key > a THEN search(w.left, a)<br />

ELSE (*old entry*)<br />

NEW(q); q.lno := line; w.last.next := q; w.last := q<br />

END<br />

END search;<br />

PROCEDURE Tabulate (w: Node);<br />

VAR m: INTEGER; item: Item;<br />

BEGIN<br />

IF w # NIL THEN<br />

Tabulate(w.left);<br />

Texts.WriteString(W, w.key); Texts.Write(W, TAB); item := w.first; m := 0;<br />

REPEAT<br />

IF m = 10 THEN<br />

Texts.WriteLn(W); Texts.Write(W, TAB); m := 0<br />

END;<br />

INC(m); Texts.WriteInt(W, item.lno, 6); item := item.next<br />

UNTIL item = NIL;<br />

Texts.WriteLn(W); Tabulate(w.right)<br />

END<br />

END Tabulate;<br />

PROCEDURE CrossRef (VAR R: Texts.Reader);<br />

VAR root: Node; (*uses global writer W*)

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

Saved successfully!

Ooh no, something went wrong!