Singly-linked list/Reversal: Difference between revisions

J
(→‎{{header|Wren}}: prepend Pascal version)
(J)
Line 46:
nymph waltz quick vex fjords Big
</pre>
 
=={{header|J}}==
Linked lists in J tend to be tremendously inefficient, and of limited utility. (And, generally speaking, their cache footprint tends to conflict with any theoretical algorithmic gains on other machines in other languages also, but J is worse here.)
 
But let's ignore those problems and implement a routine to build us a linked list and then a routine to reverse it:
 
<syntaxhighlight lang=J>
car=: 0{::]
cdr=: 1{::]
list2linkedlist=: ]`(car;<@$:@}.)@.(*@#)
reverselinkedlist=: '' {{x [`((car;<@[) $: cdr)@.(*@#@]) y }} ]</syntaxhighlight>
 
Example use:
 
<syntaxhighlight lang=J> list2linkedlist i.6
┌─┬────────────────────┐
│0│┌─┬────────────────┐│
│ ││1│┌─┬────────────┐││
│ ││ ││2│┌─┬────────┐│││
│ ││ ││ ││3│┌─┬────┐││││
│ ││ ││ ││ ││4│┌─┬┐│││││
│ ││ ││ ││ ││ ││5│││││││
│ ││ ││ ││ ││ │└─┴┘│││││
│ ││ ││ ││ │└─┴────┘││││
│ ││ ││ │└─┴────────┘│││
│ ││ │└─┴────────────┘││
│ │└─┴────────────────┘│
└─┴────────────────────┘
reverselinkedlist list2linkedlist i.6
┌─┬────────────────────┐
│5│┌─┬────────────────┐│
│ ││4│┌─┬────────────┐││
│ ││ ││3│┌─┬────────┐│││
│ ││ ││ ││2│┌─┬────┐││││
│ ││ ││ ││ ││1│┌─┬┐│││││
│ ││ ││ ││ ││ ││0│││││││
│ ││ ││ ││ ││ │└─┴┘│││││
│ ││ ││ ││ │└─┴────┘││││
│ ││ ││ │└─┴────────┘│││
│ ││ │└─┴────────────┘││
│ │└─┴────────────────┘│
└─┴────────────────────┘
</syntaxhighlight>
 
=={{header|Julia}}==
6,962

edits