Singly-linked list/Reversal: Difference between revisions

no edit summary
No edit summary
Line 470:
nymph waltz quick vex fjords Big
 
nymph waltz quick vex fjords Big
</pre>
 
=={{header|XPL0}}==
{{works with|xpl0|0.0}}
{{libheader|EXPLCodes.xpl}}
To avoid the use of pointers, the linked list is contained in two arrays; one for the name and one for the link. The code is broken down into a set of subroutines to handle the tasks of inserting items in the list, displaying the list and reversing the list. Although this results in code that is a bit larger than doing everything inline, it makes the code more modular and easier to debug and maintain.
<syntaxhighlight lang="xpl0">
inc C:\CXPL\EXPLCodes.xpl; \intrinsic declarations
 
\Program to reverse a Singly-linked list
 
int TestData;
int I;
 
\Array for use in Linked list.
 
int ListNames;
int ListLinks;
int DataInx;
 
 
proc AddItem(S);
\Insert one string in the specified Linked List
char S;
begin
ListNames(DataInx):=S;
ListLinks(DataInx):=-1;
\if not first entry, link to previous entry
if DataInx>0 then ListLinks(DataInx-1):=DataInx;
DataInx:=DataInx+1;
end;
 
 
 
proc GetReversedList;
\Return the reverse of the input list
int I,Next,Cnt;
int SA;
begin
Cnt:=DataInx;
DataInx:=0;
SA:=Reserve(Cnt * sizeof(int));
\Get names in linked order
Next:=0;
for I:=0 to Cnt-1 do
begin
SA(I):=ListNames(Next);
Next:=ListLinks(Next);
end;
\Insert them in Linked List in reverse order
for I:=Cnt-1 downto 0 do AddItem(SA(I));
end;
 
 
proc DisplayList;
\Display all items in linked list
int I,Next;
begin
Next:=0;
for I:=0 to DataInx-1 do
begin
Text(0,ListNames(Next));
Text(0," ");
Next:=ListLinks(Next);
end;
CRLF(0);
end;
 
 
begin
TestData:=["Big","fjords","vex","quick","waltz","nymph"];
ListNames:=Reserve(6 * sizeof(int));
ListLinks:=Reserve(6 * sizeof(int));
for I:=0 to 5 do AddItem(TestData(I));
DisplayList;
GetReversedList;
DisplayList;
end;
 
</syntaxhighlight>
{{out}}
<pre>
Big fjords vex quick waltz nymph
nymph waltz quick vex fjords Big
</pre>
465

edits