Singly-linked list/Reversal: Difference between revisions
Content added Content deleted
(Added Wren) |
(→{{header|Wren}}: Expanded previous answer to include in-place reversal.) |
||
Line 55: | Line 55: | ||
It's also possible to iterate backwards through the linked list using the generic reverse iterator in Wren-iterate. However, this does create a list internally and then iterates backwards through that. |
It's also possible to iterate backwards through the linked list using the generic reverse iterator in Wren-iterate. However, this does create a list internally and then iterates backwards through that. |
||
You could, of course, create a new LinkedList and then add elements to it as you iterate through them in reverse order. |
|||
However, it's also possible to reverse the LinkedList in place by successively exchanging elements at both ends. Internally, the 'exchange' method uses the indexer to swap elements. |
|||
<syntaxhighlight lang="ecmascript">import "./llist" for LinkedList |
<syntaxhighlight lang="ecmascript">import "./llist" for LinkedList |
||
import "./iterate" for Reversed |
import "./iterate" for Reversed |
||
Line 72: | Line 76: | ||
// iterate backwards by creating a list internally |
// iterate backwards by creating a list internally |
||
for (e in Reversed.new(sll)) System.write("%(e) ") |
for (e in Reversed.new(sll)) System.write("%(e) ") |
||
System.print() |
|||
// reverse the linked list in place |
|||
var i = 0 |
|||
var j = sll.count - 1 |
|||
while (i < j) { |
|||
sll.exchange(i, j) |
|||
i = i + 1 |
|||
j = j - 1 |
|||
} |
|||
// now we can iterate forwards |
|||
for (e in sll) System.write("%(e) ") |
|||
System.print()</syntaxhighlight> |
System.print()</syntaxhighlight> |
||
Line 79: | Line 95: | ||
nymph waltz quick vex fjords Big |
nymph waltz quick vex fjords Big |
||
nymph waltz quick vex fjords Big |
|||
nymph waltz quick vex fjords Big |
nymph waltz quick vex fjords Big |