Last Updated:

Why we need a dynamic variable? - Dynamic chain

Why do I need a dynamic variable? A single dynamic variable is of no interest. Of interest are various data structures created in the field of dynamic memory. Such structures are created and developed at the stage of program implementation, they can be adapted to current data, the volumes of which become known only at the stage of program implementation. Back to problem (*).

The user types a sequence of characters on the keyboard.

The end of the set is fixed by typing Ctrl+z, Enter. To store the entered characters, you must use a data structure of sufficient volume. All static data structures (data structures created in static memory) have restrictions on the number of characters entered.

Let's try to organize the storage of characters entered from the keyboard in dynamic memory. To do this, the program will describe a new data type, which is a record that contains a char type field to store the entered character, and a pointer field to the following record:

PElem=^Elem;

Elem=Record

inf:char;

next:PElem

end

At the beginning of the program, an empty chain of records is created. After each input of the next character, a new record is created and connected to the chain. Let p be a given type of PElem, x:char, then

· p:=nil; {An empty p} chain has been created

· while not eof do

begin

readln(x);

new(q);

q^.inf:=x;

q^.next:=p;

p:=q;

end; {A chain of records has been created, p is a pointer to the first entry in the chain}

Note that in the first record of the chain the last entered character is stored, in the second - the penultimate one, etc. Therefore, in order to print the characters entered from the keyboard in reverse order, you need to sequentially print out the information parts of the constructed chain.

Task: Print the third entry of the chain, if any.

writeln(p^.next^.next^.inf) {and if it doesn't exist?!}

Task: Print the k-th entry of the chain.

q:=p;

i:=1;

while (q<>nil) and (i<k) do

begin

i:=i+1;

q:=q^.next;

end;

if q<>nil then writeln(q^.inf) else writeln('no entry');

Print the information parts of the chain p.

Traditional solutionRecursive solution
Procedure prnchar(p:PElem); begin while p<>NIL do begin write(p^.inf); p=p^.next end endProcedure prnchar(p:PElem); begin if p<>NIL then begin write(p^.inf); prnchar(p^.next) end end

Task: Print the information entered from the keyboard in a direct order.

Task: "Flip" the file (Instruction – use a chain)