Singly-linked list/Traversal: Difference between revisions

m
m (→‎{{header|Wren}}: Minor tidy)
 
(47 intermediate revisions by 27 users not shown)
Line 1:
{{task|Data Structures}}[[Category:Iteration]]
[[Category:Iteration]]
 
Traverse from the beginning of a singly-linked list to the end.
 
 
{{Template:See also lists}}
<br><br>
 
=={{header|6502 Assembly}}==
 
These implementations use the zero page to hold the linked list nodes. The equivalent implementation for any arbitrary address will be left as an exercise to the reader.
 
===Using self-modifying code===
In this example, we'll create three nodes, and read the value of the last node. You can copy and paste this code into easy6502 and run it there. Note that the debugger shows that the value in the accumulator is $25, just as expected.
 
Self-modifying code is an efficient way to perform this task. Unfortunately, easy6502 does not support <code>ORG</code> directives or compile-time pointer arithmetic, so the easiest way to do this was to place a jump to the main program at the beginning and put the self-modifying section between the jump and the main program. (Easy6502's memory layout starts execution at $0600 so it was a simple matter of knowing that <code>JMP</code> takes three bytes and <code>LDA</code> takes two.)
 
The program will look up the pointer to the next node, modify the operand of the traverse function with that address, and repeat until a null pointer ($00) is read. Then it uses the same traverse function to fetch the value.
 
<syntaxhighlight lang="6502asm">define nullptr 0
jmp main
traverse:
;change the $00 to anything you want
;by writing the desired value to $0604
LDA $00,X
rts
 
main:
;create three nodes
; node 0 = #$23 stored at $0003
; node 1 = #$24 stored at $0013
; node 2 = #$25 stored at $0033
 
LDA #$03
STA $0604
;alter our code to have the starting address.
;create the linked list.
LDA #$23
STA $03
LDA #$13
STA $04
 
LDA #$24
STA $13
LDA #$33
STA $14
 
LDA #$25
STA $33
LDA #nullptr
STA $34
 
;traverse to last element and load it into A.
LDX #1
loop_traverse:
jsr traverse
;CMP #nullptr ;LDA implicitly compares to zero.
BEQ done ;if equal to nullptr, exit.
STA $0604
jmp loop_traverse
done:
dex
jsr traverse ;get the value of the last element.
brk</syntaxhighlight>
 
===Without self-modifying code===
This is mostly the same, except it uses the <code>($nn),y</code> addressing mode which is a bit slower, but can be executed on ROM cartridges no problem.
<syntaxhighlight lang="6502asm">define nullptr 0
define tempptr $fc
 
 
main:
;create three nodes
; node 0 = #$23 stored at $0003
; node 1 = #$24 stored at $0013
; node 2 = #$25 stored at $0033
 
;create the linked list.
LDA #$03
STA $FC ;store the pointer to node 0.
LDA #$00
STA $FD ;if you're using the zero page to hold your linked list entries, you need to make the high byte zero.
 
LDA #$23
STA $03
LDA #$13
STA $04
 
LDA #$24
STA $13
LDA #$33
STA $14
 
LDA #$25
STA $33
LDA #nullptr
STA $34
 
LDY #1
loop:
jsr traverse
BEQ done
STA $FC
BNE loop ;branch always
done:
DEY
JSR traverse
brk
 
traverse:
LDA ($FC),Y
rts</syntaxhighlight>
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program afficheList64.s */
 
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
 
.equ NBELEMENTS, 100 // list size
 
/*******************************************/
/* Structures */
/********************************************/
/* structure linkedlist*/
.struct 0
llist_next: // next element
.struct llist_next + 8
llist_value: // element value
.struct llist_value + 8
llist_fin:
/* Initialized data */
.data
szMessInitListe: .asciz "List initialized.\n"
szCarriageReturn: .asciz "\n"
/* datas error display */
szMessErreur: .asciz "Error detected.\n"
/* datas message display */
szMessResult: .asciz "Element No : @ value @ \n"
 
/* UnInitialized data */
.bss
lList1: .skip llist_fin * NBELEMENTS // list memory place
sZoneConv: .skip 100
/* code section */
.text
.global main
main:
ldr x0,qAdrlList1
mov x1,#0 // list init
str x1,[x0,#llist_next]
ldr x0,qAdrszMessInitListe
bl affichageMess
ldr x0,qAdrlList1
mov x1,#2
bl insertElement // add element value 2
ldr x0,qAdrlList1
mov x1,#5
bl insertElement // add element value 5
// // display elements of list
ldr x3,qAdrlList1
mov x2,#0 // ident element
1:
ldr x0,[x3,#llist_next] // end list ?
cmp x0,#0
beq 100f // yes
add x2,x2,#1
mov x0,x2 // display No element and value
ldr x1,qAdrsZoneConv
bl conversion10S
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc
mov x5,x0 // address of new string
ldr x0,[x3,#llist_value]
ldr x1,qAdrsZoneConv
bl conversion10S
mov x0,x5 // new address of message
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc
bl affichageMess
ldr x3,[x3,#llist_next] // next element
b 1b // and loop
100: // standard end of the program
mov x8, #EXIT // request to exit program
svc 0 // perform system call
qAdrszMessInitListe: .quad szMessInitListe
qAdrszMessErreur: .quad szMessErreur
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrlList1: .quad lList1
qAdrszMessResult: .quad szMessResult
qAdrsZoneConv: .quad sZoneConv
 
/******************************************************************/
/* insert element at end of list */
/******************************************************************/
/* x0 contains the address of the list */
/* x1 contains the value of element */
/* x0 returns address of element or - 1 if error */
insertElement:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x2,#llist_fin * NBELEMENTS
add x2,x2,x0 // compute address end list
1: // start loop
ldr x3,[x0,#llist_next] // load next pointer
cmp x3,#0 // = zero
csel x0,x3,x0,ne
bne 1b // no -> loop with pointer
add x3,x0,#llist_fin // yes -> compute next free address
cmp x3,x2 // > list end
bge 99f // yes -> error
str x3,[x0,#llist_next] // store next address in current pointer
str x1,[x0,#llist_value] // store element value
mov x1,#0
str x1,[x3,#llist_next] // init next pointer in next address
b 100f
99: // error
mov x0,-1
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
 
</syntaxhighlight>
 
=={{header|ACL2}}==
The standard list data type is a singly linked list.
<langsyntaxhighlight Lisplang="lisp">(defun traverse (xs)
(if (endp xs)
(cw "End.~%")
(prog2$ (cw "~x0~%" (first xs))
(traverse (rest xs)))))</langsyntaxhighlight>
 
=={{header|Action!}}==
The user must type in the monitor the following command after compilation and before running the program!<pre>SET EndProg=*</pre>
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang="action!">CARD EndProg ;required for ALLOCATE.ACT
 
INCLUDE "D2:ALLOCATE.ACT" ;from the Action! Tool Kit. You must type 'SET EndProg=*' from the monitor after compiling, but before running this program!
 
DEFINE PTR="CARD"
DEFINE NODE_SIZE="4"
TYPE ListNode=[INT data PTR nxt]
 
ListNode POINTER listBegin
 
PTR FUNC FindLast()
ListNode POINTER last
last=listBegin
IF last=0 THEN
RETURN (0)
FI
WHILE last.nxt#0
DO
last=last.nxt
OD
RETURN (last)
 
PROC Append(INT v)
ListNode POINTER n,last
 
n=Alloc(NODE_SIZE)
n.data=v
n.nxt=0
last=FindLast()
IF last THEN
last.nxt=n
ELSE
listBegin=n
FI
RETURN
 
PROC Clear()
ListNode POINTER n,next
 
n=listBegin
WHILE n
DO
next=n.nxt
Free(n,NODE_SIZE)
n=next
OD
listBegin=0
RETURN
 
PROC Traverse()
ListNode POINTER n
 
n=listBegin
PrintE("Traverse:")
Print("(")
WHILE n
DO
PrintI(n.data)
IF n.nxt THEN
Print(", ")
FI
n=n.nxt
OD
PrintE(")")
RETURN
 
PROC Main()
INT i
Put(125) PutE() ;clear screen
AllocInit(0)
listBegin=0
 
FOR i=0 TO 50
DO
Append(i*i)
OD
Traverse()
 
Clear()
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Singly-linked_list_traversal.png Screenshot from Atari 8-bit computer]
<pre>
Traverse:
(0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401, 2500)
</pre>
 
=={{header|ActionScript}}==
See [[Singly-Linked List (element)#ActionScript|Singly-Linked List (element) in ActionScript]]
<langsyntaxhighlight ActionScriptlang="actionscript">var A:Node;
//...
for(var i:Node = A; i != null; i = i.link)
{
doStuff(i);
}</langsyntaxhighlight>
 
=={{header|Ada}}==
The Ada standard container library provides a doubly-linked list. List traversal is demonstrated for the forward links.
 
<langsyntaxhighlight lang="ada">with Ada.Containers.Doubly_Linked_Lists;
with Ada.Text_Io; use Ada.Text_Io;
 
Line 41 ⟶ 366:
-- Traverse the list, calling Print for each value
The_List.Iterate(Print'access);
end traversal_example;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 49 ⟶ 374:
Linked lists are not built into ALGOL 68 ''per se'', nor any available standard library. However Linked lists are presented in standard text
book examples. Or can be manually constructed, eg:
<langsyntaxhighlight lang="algol68">MODE STRINGLIST = STRUCT(STRING value, REF STRINGLIST next);
 
STRINGLIST list := ("Big",
Line 63 ⟶ 388:
node := next OF node
OD;
print(newline)</langsyntaxhighlight>
{{out}}
<pre>
Line 70 ⟶ 395:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
% record type to hold a singly linked list of integers %
record ListI ( integer iValue; reference(ListI) next );
Line 97 ⟶ 422:
end;
 
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 106 ⟶ 431:
90210
</pre>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program afficheList.s */
 
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ READ, 3
.equ WRITE, 4
 
.equ NBELEMENTS, 100 @ list size
 
/*******************************************/
/* Structures */
/********************************************/
/* structure linkedlist*/
.struct 0
llist_next: @ next element
.struct llist_next + 4
llist_value: @ element value
.struct llist_value + 4
llist_fin:
/* Initialized data */
.data
szMessInitListe: .asciz "List initialized.\n"
szCarriageReturn: .asciz "\n"
/* datas error display */
szMessErreur: .asciz "Error detected.\n"
/* datas message display */
szMessResult: .ascii "Element No :"
sNumElement: .space 12,' '
.ascii " value : "
sValue: .space 12,' '
.asciz "\n"
 
/* UnInitialized data */
.bss
lList1: .skip llist_fin * NBELEMENTS @ list memory place
/* code section */
.text
.global main
main:
ldr r0,iAdrlList1
mov r1,#0 @ list init
str r1,[r0,#llist_next]
ldr r0,iAdrszMessInitListe
bl affichageMess
ldr r0,iAdrlList1
mov r1,#2
bl insertElement @ add element value 2
ldr r0,iAdrlList1
mov r1,#5
bl insertElement @ add element value 5
@ @ display elements of list
ldr r3,iAdrlList1
mov r2,#0 @ ident element
1:
ldr r0,[r3,#llist_next] @ end list ?
cmp r0,#0
beq 100f @ yes
add r2,#1
mov r0,r2 @ display No element and value
ldr r1,iAdrsNumElement
bl conversion10S
ldr r0,[r3,#llist_value]
ldr r1,iAdrsValue
bl conversion10S
ldr r0,iAdrszMessResult
bl affichageMess
ldr r3,[r3,#llist_next] @ next element
b 1b @ and loop
100: @ standard end of the program
mov r7, #EXIT @ request to exit program
svc 0 @ perform system call
iAdrszMessInitListe: .int szMessInitListe
iAdrszMessErreur: .int szMessErreur
iAdrszCarriageReturn: .int szCarriageReturn
iAdrlList1: .int lList1
iAdrszMessResult: .int szMessResult
iAdrsNumElement: .int sNumElement
iAdrsValue: .int sValue
 
/******************************************************************/
/* insert element at end of list */
/******************************************************************/
/* r0 contains the address of the list */
/* r1 contains the value of element */
/* r0 returns address of element or - 1 if error */
insertElement:
push {r1-r3,lr} @ save registers
mov r2,#llist_fin * NBELEMENTS
add r2,r0 @ compute address end list
1: @ start loop
ldr r3,[r0,#llist_next] @ load next pointer
cmp r3,#0 @ = zero
movne r0,r3 @ no -> loop with pointer
bne 1b
add r3,r0,#llist_fin @ yes -> compute next free address
cmp r3,r2 @ > list end
movge r0,#-1 @ yes -> error
bge 100f
str r3,[r0,#llist_next] @ store next address in current pointer
str r1,[r0,#llist_value] @ store element value
mov r1,#0
str r1,[r3,#llist_next] @ init next pointer in next address
 
100:
pop {r1-r3,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registers
mov r2,#0 @ counter length */
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call system
pop {r0,r1,r2,r7,lr} @ restaur registers
bx lr @ return
/***************************************************/
/* Converting a register to a signed decimal */
/***************************************************/
/* r0 contains value and r1 area address */
conversion10S:
push {r0-r4,lr} @ save registers
mov r2,r1 @ debut zone stockage
mov r3,#'+' @ par defaut le signe est +
cmp r0,#0 @ negative number ?
movlt r3,#'-' @ yes
mvnlt r0,r0 @ number inversion
addlt r0,#1
mov r4,#10 @ length area
1: @ start loop
bl divisionpar10U
add r1,#48 @ digit
strb r1,[r2,r4] @ store digit on area
sub r4,r4,#1 @ previous position
cmp r0,#0 @ stop if quotient = 0
bne 1b
 
strb r3,[r2,r4] @ store signe
subs r4,r4,#1 @ previous position
blt 100f @ if r4 < 0 -> end
 
mov r1,#' ' @ space
2:
strb r1,[r2,r4] @store byte space
subs r4,r4,#1 @ previous position
bge 2b @ loop if r4 > 0
100:
pop {r0-r4,lr} @ restaur registers
bx lr
/***************************************************/
/* division par 10 unsigned */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10U:
push {r2,r3,r4, lr}
mov r4,r0 @ save value
//mov r3,#0xCCCD @ r3 <- magic_number lower raspberry 3
//movt r3,#0xCCCC @ r3 <- magic_number higter raspberry 3
ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2
umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)
mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3
add r2,r0,r0, lsl #2 @ r2 <- r0 * 5
sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)
pop {r2,r3,r4,lr}
bx lr @ leave function
iMagicNumber: .int 0xCCCCCCCD
</syntaxhighlight>
 
=={{header|ATS}}==
 
I repeated the [[Singly-linked_list/Element_definition#ATS|‘Rosetta Code linear list type’]] here, so you can simply copy
the code below, compile it, and run it.
 
Also I put the executable parts in initialization rather than the main program,
to avoid being forced to ‘consume’ the list (free its memory). I felt that would be a distraction.
 
The traversal function is proven to terminate.
 
<syntaxhighlight lang="ats">(*------------------------------------------------------------------*)
 
(* The Rosetta Code linear list type can contain any vt@ype.
(The ‘@’ means it doesn’t have to be the size of a pointer.
You can read {0 <= n} as ‘for all non-negative n’. *)
dataviewtype rclist_vt (vt : vt@ype+, n : int) =
| rclist_vt_nil (vt, 0)
| {0 <= n} rclist_vt_cons (vt, n + 1) of (vt, rclist_vt (vt, n))
 
(* A lemma one will need: lists never have negative lengths. *)
extern prfun {vt : vt@ype}
lemma_rclist_vt_param
{n : int}
(lst : !rclist_vt (vt, n)) :<prf> [0 <= n] void
 
(* Proof of the lemma. *)
primplement {vt}
lemma_rclist_vt_param lst =
case+ lst of
| rclist_vt_nil () => ()
| rclist_vt_cons _ => ()
 
(*------------------------------------------------------------------*)
 
(* For simplicity, the Rosetta Code linear list traverse-and-print
routine will be specifically for lists of ‘int’. *)
 
(* Some things that will be needed. *)
#include "share/atspre_staload.hats"
 
(* The list is passed by value and will be preserved with the same
type. *)
extern fun
rclist_int_traverse_and_print
{m : int} (* ‘for all list lengths m’ *)
(lst : !rclist_vt (int, m) >> (* ! = pass by value *)
(* The new type will be the same as the old
type. *)
rclist_vt (int, m)) : void
 
implement
rclist_int_traverse_and_print {m} (lst) =
{
(* A recursive nested function that traverses the list, printing
elements along the way. *)
fun
traverse {k : int | 0 <= k}
.<k>. (* Means: ‘k must uniformly decrease towards zero.’
If so, that is proof that ‘find’ terminates. *)
(lst : !rclist_vt (int, k) >> rclist_vt (int, k)) :
void =
case+ lst of
| rclist_vt_nil () => () (* End of list. *)
| rclist_vt_cons (head, tail) =>
begin
println! (head);
traverse tail
end
 
(* The following is needed to prove that the initial k above
satisfies 0 <= k. *)
prval _ = lemma_rclist_vt_param lst
 
val _ = traverse lst
}
 
(* Now let’s try it. *)
 
(* Some convenient notation. *)
#define NIL rclist_vt_nil ()
#define :: rclist_vt_cons
overload traverse_and_print with rclist_int_traverse_and_print
 
val A = 123
val B = 789
val C = 456
 
val lst = A :: C :: B :: NIL
 
val () = traverse_and_print lst
 
(*------------------------------------------------------------------*)
 
implement
main0 () = ()</syntaxhighlight>
 
{{out}}
<pre>$ patscc -DATS_MEMALLOC_LIBC singly_linked_list_traversal.dats && ./a.out
123
456
789</pre>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">a = 1
<lang AutoHotkey>a = 1
a_next = b
b = 2
Line 127 ⟶ 738:
name := %name% . "_next"
}
}</langsyntaxhighlight>
 
=={{header|Axe}}==
<langsyntaxhighlight lang="axe">LINK(L₁,1)→A
LINK(L₁+10,2)→B
LINK(L₁+50,3)→C
Line 141 ⟶ 752:
Disp VALUE(I)▶Dec,i
NEXT(I)→I
End</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> DIM node{pNext%, iData%}
DIM a{} = node{}, b{} = node{}, c{} = node{}
Line 169 ⟶ 781:
here.pNext% = new{}
ENDPROC
</syntaxhighlight>
</lang>
{{out}}
<pre>Traverse list:
Line 178 ⟶ 790:
=={{header|C}}==
See [[Singly-Linked List (element)#C|Singly-Linked List (element) in C]].
<langsyntaxhighlight lang="c">struct link *first;
// ...
struct link *iter;
for(iter = first; iter != NULL; iter = iter->next) {
// access data, e.g. with iter->data
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
Uses the generic version of the node type located [[Singly-linked_list/Element_definition#C#|here]].
 
<syntaxhighlight lang="csharp">var current = [head of list to traverse]
while(current != null)
{
// Do something with current.Value.
 
current = current.Next;
}</syntaxhighlight>
 
Alternatively, as a for loop:
<syntaxhighlight lang="csharp">for (var current = [head of list to traverse]; current != null; current = current.Next)
{
// Do something with current.Value.
}</syntaxhighlight>
 
=={{header|C++}}==
Line 189 ⟶ 818:
{{works with|C++11}}
For each traversal version.
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <forward_list>
 
Line 197 ⟶ 826:
for (int e : list)
std::cout << e << std::endl;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
Simple iteration with a while loop.
<lang csharp>//current is the first Link in the list
while(current != null){
System.Console.WriteLine(current.item);
current = current.next;
}</lang>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="lisp">(doseq [x xs] (println x))</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(dolist (x list)
(print x))</langsyntaxhighlight>
 
Using LOOP:
 
<langsyntaxhighlight lang="lisp">(loop for x in list do (print x))</langsyntaxhighlight>
 
Using MAPC
 
<syntaxhighlight lang ="lisp">(mapc #'print list)</langsyntaxhighlight>
 
Using MAP
 
<langsyntaxhighlight lang="lisp">(map nil #'print list)</langsyntaxhighlight>
 
 
Not using builtin list iteration:
 
<langsyntaxhighlight lang="lisp">(loop for ref = list then (rest ref)
until (null ref)
do (print (first ref)))</langsyntaxhighlight>
 
=={{header|Computer/zero Assembly}}==
A linked list can be implemented as a chain of CONS cells, where each cell is made up of two neighbouring memory locations: the CAR, storing an item of data, and the CDR, storing the address of the next cell in the list. The CDR of the last cell contains not an address but a special <tt>NIL</tt> value that is guaranteed not to be a valid address; in this implementation, we use 0 to represent <tt>NIL</tt>. The order of CONS cells in memory is of course entirely unimportant. For the sake of example, this program traverses the list <tt>'(1 2 3 4 5 6)</tt> and halts with the final value in the accumulator. The program is reasonably straightforward, but it does make some use of instruction arithmetic (self-modifying code).
<langsyntaxhighlight lang="czasm">start: LDA load
ADD car ; head of list
STA ldcar
Line 264 ⟶ 885:
26,27: 3, 30
28,29: 1, 22
30,31: 4, 24</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">struct SLinkedNode(T) {
T data;
typeof(this)* next;
Line 281 ⟶ 902:
write(p.data, " ");
writeln();
}</langsyntaxhighlight>
{{out}}
<pre>1 2 3 4 </pre>
===Alternative Version===
Using tango's collections (written by Doug Lea, ported to D):
<langsyntaxhighlight lang="d">import tango.io.Stdout;
import tango.util.collection.LinkSeq;
 
Line 296 ⟶ 917:
foreach (val; m)
Stdout(val).newline;
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
<langsyntaxhighlight lang="delphi">uses system ;
type
Line 320 ⟶ 941:
while not (pList^.Next = NIL) do pList := pList^.Next ;
end;</langsyntaxhighlight>
 
=={{header|Dyalect}}==
 
Dyalect doesn't support linked lists out of the box, but it is fairly simple to implement one:
 
<syntaxhighlight lang="dyalect">type List = Cons(value, tail) or Nil()
with Lookup
static func List.FromArray(xs) {
var list = List.Nil()
var len = xs.Length()
for i in (len-1)^-1..0 {
list = List.Cons(xs[i], list)
}
return list
}
func List.Iterate() {
var xs = this
do {
match xs {
Cons(value, tail) => {
yield value
xs = tail
},
Nil() => {
yield break
}
}
} while true
}
var xs = List.FromArray([1..10])
for x in xs {
print(x)
}</syntaxhighlight>
 
It is also possible to provide an ad hoc solution to the problem:
 
{{trans|E}}
 
<syntaxhighlight lang="dyalect">var xs = (1, (2, (3, (4, (5, (6, (7, (8, (9, (10, nil))))))))))
 
while xs is (value, tail) {
print(value)
xs = tail
}</syntaxhighlight>
 
Here a linked list is emulated using tuples.
 
=={{header|E}}==
Using a list made from tuples:
<langsyntaxhighlight lang="e">var linkedList := [1, [2, [3, [4, [5, [6, [7, null]]]]]]]
 
while (linkedList =~ [value, next]) {
println(value)
linkedList := next
}</langsyntaxhighlight>
 
Using a list made from the structure defined at [[Singly-Linked List (element)#E|Singly-Linked List (element)]]:
<langsyntaxhighlight lang="e">var linkedList := makeLink(1, makeLink(2, makeLink(3, empty)))
 
while (!(linkedList.null())) {
println(linkedList.value())
linkedList := linkedList.next()
}</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
Lists - linked-lists - are '''the''' fundamental data type in EchoLisp. A lot of fuctions exist to scan lists or operate on successive elements.
<langsyntaxhighlight lang="lisp">
(define friends '( albert ludwig elvis 🌀))
 
Line 367 ⟶ 1,041:
(foldl + 0 L) → 500500 ; 1000 * 1001 / 2
 
</syntaxhighlight>
</lang>
 
=={{header|Ela}}==
<langsyntaxhighlight lang="ela">traverse [] = []
traverse (x::xs) = x :: traverse xs</langsyntaxhighlight>
 
This function traverses a list and constructs a new list at the same time. For a list in Ela it is the same as identity function, e.g. traverse [1,2,3] == [1,2,3]. However it can be useful in some cases. For example, to enforce a lazy list:
 
<langsyntaxhighlight lang="ela">xs = [& x \\ x <- [1..1000]]//lazy list
 
traverse xs</syntaxhighlight>
 
traverse xs</lang>
=={{header|Elena}}==
Simple iteration with a while loop.
<langsyntaxhighlight lang="elena">
while($nil != current){
console printLine(current .Item).;
current := current Next.Next
}</langsyntaxhighlight>
 
=={{header|Erlang}}==
Line 396 ⟶ 1,071:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">: list-each ( linked-list quot: ( data -- ) -- )
[ [ data>> ] dip call ]
[ [ next>> ] dip over [ list-each ] [ 2drop ] if ] 2bi ; inline recursive
Line 406 ⟶ 1,081:
[ B <linked-list> list-insert ] keep
 
[ . ] list-each</langsyntaxhighlight>
{{out}}
<pre>
Line 416 ⟶ 1,091:
=={{header|Fantom}}==
Using the definitions from [[Singly-Linked_List_(element_insertion)]]:
<langsyntaxhighlight lang="fantom"> // traverse the linked list
Node? current := a
while (current != null)
Line 422 ⟶ 1,097:
echo (current.value)
current = current.successor
}</langsyntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: last ( list -- end )
begin dup @ while @ repeat ;</langsyntaxhighlight>
And here is a function to walk a list, calling an XT on each data cell:
<langsyntaxhighlight lang="forth">: walk ( a xt -- )
>r begin ?dup while
dup cell+ @ r@ execute
@ repeat r> drop ;</langsyntaxhighlight>
 
Testing code:
Line 438 ⟶ 1,113:
=={{header|Fortran}}==
Fortran 95. See [[Singly-Linked List (element)#Fortran|Singly-Linked List (element) in Fortran]].
<langsyntaxhighlight lang="fortran">subroutine traversal(list,proc)
type(node), target :: list
type(node), pointer :: current
Line 451 ⟶ 1,126:
current => current%next
end do
end subroutine traversal</langsyntaxhighlight>
Print data from all nodes of a singly-linked list:
<langsyntaxhighlight lang="fortran">subroutine printNode(data)
real, intent(in) :: data
write (*,*) data
Line 461 ⟶ 1,136:
type(node), intent(in) :: list
call traversal(list,printNode)
end subroutine printAll</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
Requires the type definition and node insertion routine [[Singly-linked_list/Element_definition#FreeBASIC|here]] and [[Singly-linked_list/Element_insertion#FreeBASIC|here]] respectively. Also includes a routine for allocating space for a node.
 
<syntaxhighlight lang="freebasic">#define NULL 0
 
function alloc_ll_int( n as integer ) as ll_int ptr
dim as ll_int ptr ret = allocate(sizeof(ll_int))
ret->n = n
ret->nxt = NULL
return ret
end function
 
sub traverse_ll_int( head as ll_int ptr )
dim as ll_int ptr curr = head
while curr <> NULL
print curr->n
curr = curr->nxt
wend
end sub
 
dim as ll_int ptr curr, head = alloc_ll_int( 0 ), node
dim as integer i
curr=head
for i = 1 to 50
'build a list to traverse. This is basically a traversal itself...
node = alloc_ll_int( i )
insert_ll_int( curr, node )
curr = curr->nxt
next i
 
traverse_ll_int( head )</syntaxhighlight>
 
=={{header|Go}}==
See [[Singly-Linked List (element)#Go|Singly-Linked List (element) in Go]].
<langsyntaxhighlight lang="go">start := &Ele{"tacos", nil}
end := start.Append("burritos")
end = end.Append("fajitas")
Line 471 ⟶ 1,178:
for iter := start; iter != nil; iter = iter.Next {
fmt.Println(iter)
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
Lists are ubiquitous in Haskell, simply use Haskell's <em>map</em> library function:
<langsyntaxhighlight lang="haskell">map (>5) [1..10] -- [False,False,False,False,False,True,True,True,True,True]
 
map (++ "s") ["Apple", "Orange", "Mango", "Pear"] -- ["Apples","Oranges","Mangos","Pears"]
Line 483 ⟶ 1,190:
traverse :: [a] -> [a]
traverse list = map func list
where func a = -- ...do something with a</langsyntaxhighlight>
 
Note that the <em>traverse</em> function is polymorphic; denoted by <em>traverse :: [a] -> [a]</em> where <em>a</em> can be of any type.
Line 489 ⟶ 1,196:
=={{header|Icon}} and {{header|Unicon}}==
Using either the record or class-based definitions from [[Singly-Linked List (element)#Icon_and_Unicon|Singly-Linked List (element) in Icon and Unicon]]:
<langsyntaxhighlight Iconlang="icon">procedure main ()
ns := Node(1, Node(2, Node (3)))
until /ns do { # repeat until ns is null
Line 495 ⟶ 1,202:
ns := ns.successor
}
end</langsyntaxhighlight>
Prints the numbers 1, 2, 3 in turn.
 
=={{header|J}}==
Using the implementation mentioned at [[Singly-Linked List (element)#J|Singly-Linked List (element) in J]], we can apply a function <tt>foo</tt> to each node the following way:
<langsyntaxhighlight Jlang="j">foo"0 {:"1 list</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|1.5+}}
For Java.util.LinkedList<T>, use a for each loop (from [[Loop Structures]]):
<langsyntaxhighlight lang="java">LinkedList<Type> list = new LinkedList<Type>();
 
for(Type i: list){
//each element will be in variable "i"
System.out.println(i);
}</langsyntaxhighlight>
Note that <code>java.util.LinkedList</code> can also perform as a stack, queue, or doubly-linked list.
 
=={{header|JavaScript}}==
Extending [[Singly-Linked_List_(element)#JavaScript]]
<langsyntaxhighlight lang="javascript">LinkedList.prototype.traverse = function(func) {
func(this);
if (this.next() != null)
Line 526 ⟶ 1,233:
 
var head = createLinkedListFromArray([10,20,30,40]);
head.print();</langsyntaxhighlight>
Uses the <code>print()</code> function from [[Rhino]]
 
Line 532 ⟶ 1,239:
Alternatively, translating the [[#Haskell | Haskell]] examples in terms of JavaScript's Array.map, Array.reduce, and Array.forEach:
 
<langsyntaxhighlight JavaScriptlang="javascript">var map = function (fn, list) {
return list.map(fn);
},
Line 577 ⟶ 1,284:
/* Orange */
/* Mango */
/* Pear */</langsyntaxhighlight>
 
=={{header|Joy}}==
<syntaxhighlight lang="joy">['a 'b 'c '\n] [putch] step.</syntaxhighlight>
 
=={{header|jq}}==
{{works with|jq}}
In practice, jq's arrays would probably be used whenever a singly-linked list might otherwise be used, but to illustrate traversal through a linked list, let us use JSON objects with keys "car" and "cdr", where a "cdr" value of null indicates the end of the linked list.
'''Works with gojq, the Go implementation of jq'''
 
For context see [[Singly-linked_list/Element_definition#jq]].
For example:
<lang jq>def test_list:
{ "car": 1, "cdr": { "car": 2, "cdr": { "car": 3, "cdr": null }}};
</lang>
 
Here we define a "map" filter as well as a traversal filter. The "map" filter is similar to the built-in `map` in that it can be used to remove items as per the comment below.
To illustrate iteration along the links:
<syntaxhighlight lang="jq">
def traverse: .car, (.cdr | if . == null then empty else traverse end);
# Produce a stream of the items in the input SLL.
def items:
while(.; .next) | .item;
 
def to_singly_linked_list(s):
A more mind-bending approach is to use recurse/1:
reduce ([s]|reverse[]) as $item (null; {$item, next:.});
def traverse2: recurse( .cdr ) | .car;
 
# If f evaluates to empty at any item, that item is removed;
'''test_list | traverse''' and '''test_list | traverse2''' produce identical results: a stream of the "car" values.
# if f evaluates to more than one item, all are added separately.
def map_singly_linked_list(f): to_singly_linked_list( items | f );</syntaxhighlight>
'''Examples'''
<syntaxhighlight lang="jq">{
"item": 1,
"next": {
"item": 2,
"next": null
}
}
| reduce items as $item (null; .+$item),
map_singly_linked_list(- .)</syntaxhighlight>
{{out}}
<pre>
3
{
"item": -1,
"next": {
"item": -2,
"next": null
}
}
</pre>
 
=={{header|Julia}}==
Line 599 ⟶ 1,333:
Julia let you implement list traversal very easily: see [[Singly-linked_list/Element_definition#Julia]] for the <tt>LinkedList</tt> struct definition.
 
<langsyntaxhighlight lang="julia">Base.start(ll::LinkedList) = ll.head
Base.done(ll::LinkedList{T}, st::AbstractNode{T}) where T = st isa EmptyNode
Base.next(ll::LinkedList{T}, st::AbstractNode{T}) where T = st.data, st.next
Line 610 ⟶ 1,344:
for n in lst
print(n, " ")
end</langsyntaxhighlight>
 
=={{header|Kotlin}}==
Lists in Kotlin may be instanciated from Java classes or from Kotlin methods or extensions.
<langsyntaxhighlight lang="scala">fun main(args: Array<String>) {
val list = IntRange(1, 50).toList()
 
Line 622 ⟶ 1,356:
// list iterator:
list.asReversed().forEach { print("%4d ".format(it)); if (it % 10 == 1) println() }
}</langsyntaxhighlight>
{{out}}
<pre> 1 2 3 4 5 6 7 8 9 10
Line 634 ⟶ 1,368:
20 19 18 17 16 15 14 13 12 11
10 9 8 7 6 5 4 3 2 1</pre>
 
=={{header|Limbo}}==
Lists are a built-in type in Limbo.
<langsyntaxhighlight Limbolang="limbo">implement Command;
 
include "sys.m";
Line 655 ⟶ 1,390:
sys->print("%d\n", hd l);
# the unary 'hd' operator gets the head of a list
}</langsyntaxhighlight>
 
=={{header|Logo}}==
LAST is already a Logo built-in, but it could be defined this way:
<langsyntaxhighlight lang="logo">to last :list
if empty? bf :list [output first :list]
output last bf :list
end</langsyntaxhighlight>
 
=={{header|Logtalk}}==
The built-in list type can be viewed as a singly linked list.
Traversing can be trivially done using a tail-recursive predicate:
<langsyntaxhighlight lang="logtalk">
:- object(singly_linked_list).
 
Line 681 ⟶ 1,416:
 
:- end_object.
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="text">
| ?- singly_linked_list::show.
1
Line 689 ⟶ 1,424:
3
yes
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Print /@ {"rosettacode", "kitten", "sitting", "rosettacode", "raisethysword"}</syntaxhighlight>
{{out}}
->
<pre>rosettacode
kitten
sitting
rosettacode
raisethysword</langpre>
 
=={{header|MATLAB}} / {{header|Octave}}==
Line 704 ⟶ 1,439:
Matlab and Octave do not have pointers.
Linked lists are implemented as vectors (i.e. arrays of size 1xN)
<langsyntaxhighlight Matlablang="matlab">list = 1:10;
for k=1:length(list)
printf('%i\n',list(k))
end; </langsyntaxhighlight>
 
It is recommended to avoid loops and "vectorize" the code:
 
<langsyntaxhighlight Matlablang="matlab"> printf('%d\n', list(:)); </langsyntaxhighlight>
 
=={{header|MiniScript}}==
We're choosing here to use the built-in list type, rather than make our own from scratch, since this is more representative of how one is likely to actually use MiniScript.
<syntaxhighlight lang="miniscript">myList = [2, 4, 6, 8]
for i in myList
print i
end for</syntaxhighlight>
{{out}}
<pre>
2
4
6
8
</pre>
 
=={{header|Nanoquery}}==
{{trans|C}}
See [[Singly-Linked List (element)#Nanoquery|Singly-Linked List (element) in Nanoquery]].
<syntaxhighlight lang="nanoquery">first = new(link)
//
for (iter = first) (iter != null) (iter = iter.next)
println iter.data
end</syntaxhighlight>
 
=={{header|NewLISP}}==
<langsyntaxhighlight NewLISPlang="newlisp">(dolist (x '(a b c d e))
(println x))</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">type Node[T] = ref object
next: Node[T]
data: T
Line 738 ⟶ 1,496:
iterator items(a: Node) =
var x = a
while not x != nil.isNil:
yield x
x = x.next
 
for item in a:
echo item.data</langsyntaxhighlight>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
for(node := head; node <> Nil; node := node->GetNext();) {
node->GetValue()->PrintLine();
};
</syntaxhighlight>
</lang>
 
=={{header|Objective-C}}==
(See [[Singly-Linked List (element)]])
<langsyntaxhighlight lang="objc">RCListElement *current;
for(current=first_of_the_list; current != nil; current = [current next] )
{
// to get the "datum":
// id dat_obj = [current datum];
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml"># let li = ["big"; "fjords"; "vex"; "quick"; "waltz"; "nymph"] in
List.iter print_endline li ;;
big
Line 770 ⟶ 1,528:
waltz
nymph
- : unit = ()</langsyntaxhighlight>
 
=={{header|Odin}}==
<syntaxhighlight lang="odin">package main
 
import "core:fmt"
 
Node :: struct {
data: rune,
next: ^Node,
}
 
insert_after :: proc(node, new_node: ^Node) {
new_node.next = node.next
node.next = new_node
}
 
main :: proc() {
a := new(Node)
a.data = 'A'
 
b := new(Node)
b.data = 'B'
 
c := new(Node)
c.data = 'C'
 
insert_after(a, b) // A -> B
insert_after(a, c) // A -> C -> B
 
for n := a; n != nil; n = n.next {
fmt.print(n.data)
} // prints: ACB
}
</syntaxhighlight>
 
=={{header|Oforth}}==
Line 778 ⟶ 1,570:
Because forEachNext is defined, a linked list responds to all methods defined for Collections : apply, map, filter, ....
 
<langsyntaxhighlight Oforthlang="oforth">: testLink LinkedList new($A, null) dup add($B) dup add($C) ;
testLink apply(#println)</langsyntaxhighlight>
 
{{out}}
Line 790 ⟶ 1,582:
=={{header|ooRexx}}==
See [[Singly-linked_list/Element_definition#ooRexx|Singly-Linked List/Element Definition in ooRexx]] for the full class definition.
<langsyntaxhighlight ooRexxlang="oorexx">list=.list~of('A','B','X')
say "Manual list traversal"
index=list~first
Line 802 ⟶ 1,594:
do value over list
say value
end</langsyntaxhighlight>
{{out}}
<pre>Manual list traversal
Line 816 ⟶ 1,608:
 
=={{header|Pascal}}==
See [[Singly-linked_list/Traversal#Delphi | Delphi]]
 
=={{header|Peloton}}==
This makes a list of the Chinese Public Holiday and lists them first till last and then last till first.
<langsyntaxhighlight lang="sgml"><@ LETCNSLSTLIT>public holidays|開國紀念日^和平紀念日^婦女節、兒童節合併假期^清明節^國慶日^春節^端午節^中秋節^農曆除夕</@>
<@ OMT>From First to Last</@>
<@ ITEFORSZELSTLIT>public holidays|
Line 828 ⟶ 1,620:
<@ ITEFORSZELSTLIT>public holidays|
<@ SAYLST>...</@><@ ACTMOVBKWLST>...</@>
</@></langsyntaxhighlight>
This variable length Simplified Chinese rendition of the same code is
<langsyntaxhighlight lang="sgml"><# 指定构造列表字串>public holidays|開國紀念日^和平紀念日^婦女節、兒童節合併假期^清明節^國慶日^春節^端午節^中秋節^農曆除夕</#>
<# 忽略>From First to Last</#>
<# 迭代迭代次数结构大小列表字串>public holidays|
Line 838 ⟶ 1,630:
<# 迭代迭代次数结构大小列表字串>public holidays|
<# 显示列表>...</#><# 运行移位指针向后列表>...</#>
</#></langsyntaxhighlight>
 
=={{header|Perl}}==
We use Class::Tiny to get OO functionality with minimal effort.
<langsyntaxhighlight lang="perl">package SSL_Node;
use strict;
use Class::Tiny qw( val next );
Line 871 ⟶ 1,663:
$node = $node->next;
}
print "\n";</langsyntaxhighlight>
{{out}}
<pre>10... 9... 8... 7... 6... 5... 4... 3... 2... 1...
</pre>
 
=={{header|Perl 6}}==
Built-in list processing in Perl is not specifically based on singly-linked lists,
but works at a higher abstraction level that encapsulates such implementation choices. Nonetheless, it's trivial to use the <tt>Pair</tt> type to build what is essentially a Lisp-style cons list, and in fact, the <tt>=></tt> pair constructor is right associative for precisely that reason.
We traverse such a list here using a 3-part loop:
<lang perl6>my $list = 1 => 2 => 3 => 4 => 5 => 6 => Mu;
 
loop (my $l = $list; $l; $l.=value) {
say $l.key;
}</lang>
{{out}}
<pre>1
2
3
4
5
6</pre>
It would be pretty easy to make such lists iterable as normal Perl lists,
if anyone really cared to...
 
Well, shoot, let's just go ahead and do it.
We'll pretend the <tt>Pair</tt> type is really a list type.
(And we show how you turn an ordinary list into a cons list using a reduction.
Note how the <tt>[=>]</tt> reduction is also right associative,
just like the base operator.)
<lang perl6>use MONKEY-TYPING;
augment class Pair {
method traverse () {
gather loop (my $l = self; $l; $l.=value) {
take $l.key;
}
}
}
 
my $list = [=>] 'Ⅰ' .. 'Ⅻ', Mu;
say ~$list.traverse;</lang>
 
{{out}}
<pre>Ⅰ Ⅱ Ⅲ Ⅳ Ⅴ Ⅵ Ⅶ Ⅷ Ⅸ Ⅹ Ⅺ Ⅻ</pre>
 
=={{header|Phix}}==
See also [[Singly-linked_list/Element_removal#Phix|Removal]].
<lang Phix>enum NEXT,DATA
<!--<syntaxhighlight lang="phix">(phixonline)-->
constant empty_sll = {{1}}
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
sequence sll = empty_sll
<span style="color: #008080;">enum</span> <span style="color: #000000;">NEXT</span><span style="color: #0000FF;">,</span><span style="color: #000000;">DATA</span>
 
<span style="color: #008080;">constant</span> <span style="color: #000000;">empty_sll</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #004600;">NULL</span><span style="color: #0000FF;">}}</span>
procedure insert_after(object data, integer pos=length(sll))
<span style="color: #004080;">sequence</span> <span style="color: #000000;">sll</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">deep_copy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">empty_sll</span><span style="color: #0000FF;">)</span>
sll = append(sll,{sll[pos][NEXT],data})
sll[pos][NEXT] = length(sll)
<span style="color: #008080;">procedure</span> <span style="color: #000000;">insert_after</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">data</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">pos</span><span style="color: #0000FF;">=</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sll</span><span style="color: #0000FF;">))</span>
end procedure
<span style="color: #000000;">sll</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sll</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">sll</span><span style="color: #0000FF;">[</span><span style="color: #000000;">pos</span><span style="color: #0000FF;">][</span><span style="color: #000000;">NEXT</span><span style="color: #0000FF;">],</span><span style="color: #000000;">data</span><span style="color: #0000FF;">})</span>
 
<span style="color: #000000;">sll</span><span style="color: #0000FF;">[</span><span style="color: #000000;">pos</span><span style="color: #0000FF;">][</span><span style="color: #000000;">NEXT</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sll</span><span style="color: #0000FF;">)</span>
insert_after("ONE")
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
insert_after("TWO")
insert_after("THREE")
<span style="color: #000000;">insert_after</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"ONE"</span><span style="color: #0000FF;">)</span>
 
<span style="color: #000000;">insert_after</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"TWO"</span><span style="color: #0000FF;">)</span>
?sll
<span style="color: #000000;">insert_after</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"THREE"</span><span style="color: #0000FF;">)</span>
 
procedure show()
<span style="color: #0000FF;">?</span><span style="color: #000000;">sll</span>
integer idx = sll[1][NEXT]
while idx!=1 do
<span style="color: #008080;">procedure</span> <span style="color: #000000;">show</span><span style="color: #0000FF;">()</span>
?sll[idx][DATA]
<span style="color: #004080;">integer</span> <span style="color: #000000;">idx</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">sll</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">][</span><span style="color: #000000;">NEXT</span><span style="color: #0000FF;">]</span>
idx = sll[idx][NEXT]
<span style="color: #008080;">while</span> <span style="color: #000000;">idx</span><span style="color: #0000FF;">!=</span><span style="color: #004600;">NULL</span> <span style="color: #008080;">do</span>
end while
<span style="color: #0000FF;">?</span><span style="color: #000000;">sll</span><span style="color: #0000FF;">[</span><span style="color: #000000;">idx</span><span style="color: #0000FF;">][</span><span style="color: #000000;">DATA</span><span style="color: #0000FF;">]</span>
end procedure
<span style="color: #000000;">idx</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">sll</span><span style="color: #0000FF;">[</span><span style="color: #000000;">idx</span><span style="color: #0000FF;">][</span><span style="color: #000000;">NEXT</span><span style="color: #0000FF;">]</span>
show()</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">show</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
{{2},{3,"ONE"},{4,"TWO"},{10,"THREE"}}
"ONE"
"TWO"
Line 949 ⟶ 1,706:
=={{header|PicoLisp}}==
We might use map functions
<langsyntaxhighlight PicoLisplang="picolisp">(mapc println '(a "cde" (X Y Z) 999))</langsyntaxhighlight>
or flow control functions
<langsyntaxhighlight PicoLisplang="picolisp">(for X '(a "cde" (X Y Z) 999)
(println X) )</langsyntaxhighlight>
{{out}} for both cases:
<pre>a
Line 960 ⟶ 1,717:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">*process source attributes xref or(!);
/*********************************************************************
* 25.10.2013 Walter Pachl
Line 1,000 ⟶ 1,757:
p=p->next;
End;
End;</langsyntaxhighlight>
{{out}}
<pre> 1 Walter
Line 1,008 ⟶ 1,765:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure traverse(*node.MyData)
While *node
;access data, i.e. PrintN(Str(*node\Value))
Line 1,016 ⟶ 1,773:
 
;called using
traverse(*firstnode.MyData)</langsyntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">for node in lst:
print node.value</langsyntaxhighlight>
Any Python class can define ''next()'' and ''__iter__()'' methods so that it can be used with the normal ''for'' iteration syntax.
In this example the "lst" could be an instance of any Python list, tuple, dictionary, or any sort of object which defines an iterator.
It could also be a generator (a type of function which ''yields'' results upon each successive invocation).
The notion of a "singly linked list" is somewhat more primitive than normal Python built-in objects.
<langsyntaxhighlight lang="python">class LinkedList(object):
"""USELESS academic/classroom example of a linked list implemented in Python.
Don't ever consider using something this crude! Use the built-in list() type!
Line 1,047 ⟶ 1,804:
for value in lst:
print value,;
print</langsyntaxhighlight>
{{out}}
<pre>
Line 1,057 ⟶ 1,814:
Since singly-linked lists that are made of <tt>cons</tt> cells are one of the most common primitive types in Racket, there is a lot of built-in functionality that scans these lists:
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 1,087 ⟶ 1,844:
(mfor-each displayln ml)
(for ([x (in-mlist ml)]) (displayln x))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
===With <tt>Pair</tt>===
 
Built-in list processing in Raku is not specifically based on singly-linked lists,
but works at a higher abstraction level that encapsulates such implementation choices. Nonetheless, it's trivial to use the <tt>Pair</tt> type to build what is essentially a Lisp-style cons list, and in fact, the <tt>=></tt> pair constructor is right associative for precisely that reason.
We traverse such a list here using a 3-part loop:
<syntaxhighlight lang="raku" line>my $list = 1 => 2 => 3 => 4 => 5 => 6 => Mu;
 
loop (my $l = $list; $l; $l.=value) {
say $l.key;
}</syntaxhighlight>
{{out}}
<pre>1
2
3
4
5
6</pre>
It would be pretty easy to make such lists iterable as normal Raku lists,
if anyone really cared to...
 
Well, shoot, let's just go ahead and do it.
We'll pretend the <tt>Pair</tt> type is really a list type.
(And we show how you turn an ordinary list into a cons list using a reduction.
Note how the <tt>[=>]</tt> reduction is also right associative,
just like the base operator.)
<syntaxhighlight lang="raku" line>use MONKEY-TYPING;
augment class Pair {
method traverse () {
gather loop (my $l = self; $l; $l.=value) {
take $l.key;
}
}
}
 
my $list = [=>] 'Ⅰ' .. 'Ⅻ', Mu;
say ~$list.traverse;</syntaxhighlight>
 
{{out}}
<pre>Ⅰ Ⅱ Ⅲ Ⅳ Ⅴ Ⅵ Ⅶ Ⅷ Ⅸ Ⅹ Ⅺ Ⅻ</pre>
 
===With custom type===
 
Extending <tt>class Cell</tt> from [[Singly-linked_list/Element_definition#Raku]]:
 
<syntaxhighlight lang="raku" line> method Seq {
self, *.next ...^ !*
}</syntaxhighlight>
 
Usage:
 
<syntaxhighlight lang="raku" line>my $list = (cons 10, (cons 20, (cons 30, Nil)));
 
for $list.Seq -> $cell {
say $cell.value;
}</syntaxhighlight>
{{out}}
<pre>10
20
30</pre>
 
=={{header|Retro}}==
<langsyntaxhighlight Retrolang="retro">: traverse ( l- ) repeat @ 0; again ;</langsyntaxhighlight>
Or, using combinators:
<langsyntaxhighlight Retrolang="retro">last [ drop ] ^types'LIST each@</langsyntaxhighlight>
With combinators you can also perform an operation on each element in a linked list:
<langsyntaxhighlight Retrolang="retro">last [ @d->name puts space ] ^types'LIST each@</langsyntaxhighlight>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/* REXX ********************************************************************
* 25.10.2013 Walter Pachl
*********************************************************************/
Line 1,112 ⟶ 1,931:
Say c elem.c.val
c=elem.c.next
End</langsyntaxhighlight>
 
=={{header|Ruby}}==
referring to [[Singly-Linked List (element)#Ruby]] and [[Singly-Linked List (element insertion)#Ruby]]
<langsyntaxhighlight lang="ruby">head = ListNode.new("a", ListNode.new("b", ListNode.new("c")))
head.insertAfter("b", "b+")
 
Line 1,128 ⟶ 1,947:
print current.value, ","
end while current = current.succ
puts</langsyntaxhighlight>
{{out}}
<pre>a,b,b+,c,
Line 1,134 ⟶ 1,953:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">list$ = "now is the time for all good men"
for lnk = 1 to 8
print lnk;"->";word$(list$,lnk)
next lnk</langsyntaxhighlight>
{{out}}
<pre>1->now
Line 1,155 ⟶ 1,974:
The following will demonstrate iteration all three ways.
 
<langsyntaxhighlight lang="rust">//
//
// Iteration by value (simply empties the list as the caller now owns all values)
Line 1,232 ⟶ 2,051:
}
 
}</langsyntaxhighlight>
 
=={{header|Scala}}==
You can use pattern matching for traversing a list.
 
<langsyntaxhighlight lang="scala">
/*
Here is a basic list definition
Line 1,253 ⟶ 2,072:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(define (traverse seq func)
(if (null? seq)
'()
(begin
(func (car seq))
(traverse (cdr seq) func))))</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var list = 'a':'b':'c':nil;
#var list = ['a', ['b', ['c']]];
#var list = Pair.new('a', Pair.new('b', Pair.new('c', nil)));
Line 1,270 ⟶ 2,089:
for (var l = list; l != nil; l = l[1]) {
say l[0];
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,280 ⟶ 2,099:
=={{header|SSEM}}==
Linked lists are a comparatively easy data structure to implement in machine language, although the SSEM does not really have enough storage to make them practically useful. A linked list consists of any number of cons cells, i.e. pairs of successive words in storage where the first word holds a data item and the second holds either a pointer to the next pair or else a special nil value—represented here by 0, although any negative address would also work—indicating we have reached the end of the list. The pairs or cons cells can be scattered arbitrarily through the available storage space. This program traverses the list <tt>'(1 2 3)</tt>, and halts with the last value in the accumulator. It makes some use of instruction arithmetic (self-modifying code).
<langsyntaxhighlight lang="ssem">11101000000000100000000000000000 0. -23 to c
10011000000000010000000000000000 1. Sub. 25
10010000000001100000000000000000 2. c to 9
Line 1,311 ⟶ 2,130:
01011000000000000000000000000000 29. pointer: 26
11000000000000000000000000000000 30. 3
00000000000000000000000000000000 31. 0 (nil)</langsyntaxhighlight>
SSEM programs can be difficult to take in: the constant negations, subtractions, and indirect jumps often obscure the underlying algorithm. To clarify what is going on, here is a pseudocode version of the same program:
<pre>start: load loadZero
Line 1,340 ⟶ 2,159:
Using the class definition from [[Singly-Linked List (element)#Tcl|Singly-Linked List (element)]] (and bearing in mind the general notes on lists given there) we'll modify that class so that lists have an iteration method...
{{works with|Tcl|8.6}}
<langsyntaxhighlight lang="tcl">oo::define List {
method for {varName script} {
upvar 1 $varName var
Line 1,350 ⟶ 2,169:
}
}
}</langsyntaxhighlight>
Now, a demonstration...
<langsyntaxhighlight lang="tcl">set list {}
foreach n {1 3 5 7 2 4 6 8} {
set list [List new $n $list]
Line 1,358 ⟶ 2,177:
$list for x {
puts "we have a $x in the list"
}</langsyntaxhighlight>
 
=={{header|Trith}}==
<langsyntaxhighlight lang="trith">[1 2 3 4 5] [print] each</langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
<langsyntaxhighlight lang="vbnet">Private Sub Iterate(ByVal list As LinkedList(Of Integer))
Dim node = list.First
Do Until node Is Nothing
node = node.Next
Loop
End Sub</langsyntaxhighlight>
 
=={{header|Wart}}==
<langsyntaxhighlight lang="wart">each x '(1 2 3)
prn x</langsyntaxhighlight>
 
=={{header|Wren}}==
{{libheader|Wren-llist}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./llist" for LinkedList
import "./fmt" for Fmt
 
//create a new linked list and add the first 50 positive integers to it
var ll = LinkedList.new(1..50)
 
// traverse the linked list
for (i in ll) {
Fmt.write("$4d ", i)
if (i % 10 == 0) System.print()
}</syntaxhighlight>
 
{{out}}
<pre>
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">def \Node\ Link, Data; \linked list element definition
<lang XPL0>repeat Node:= Node(0) until Node=0</lang>
int Node, List;
[Node:= List; \traverse the linked list
while Node # 0 do
Node:= Node(Link); \move to next node
]</syntaxhighlight>
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">// Rosetta Code problem: http://rosettacode.org/wiki/Singly-linked_list/Element_insertion & removal & traverse
// by Galileo, 02/2022
 
FIL = 1 : DATO = 2 : LINK = 3
countNodes = 0 : Nodes = 10
 
dim list(Nodes, 3)
 
 
sub searchNode(node)
local i, prevNode
for i = 1 to countNodes
if i = node break
prevNode = list(prevNode, LINK)
next
return prevNode
end sub
 
sub insertNode(node, newNode, after)
local prevNode, i
prevNode = searchNode(node)
if after prevNode = list(prevNode, LINK)
for i = 1 to Nodes
if not list(i, FIL) break
next
list(i, FIL) = true
list(i, DATO) = newNode
list(i, LINK) = list(prevNode, LINK)
list(prevNode, LINK) = i
countNodes = countNodes + 1
if countNodes = Nodes then Nodes = Nodes + 10 : redim list(Nodes, 3) : end if
end sub
 
 
sub removeNode(n)
local prevNode, node
prevNode = searchNode(n)
node = list(prevNode, LINK)
list(prevNode, LINK) = list(node, LINK)
list(node, FIL) = false
countNodes = countNodes - 1
end sub
 
 
sub printNode(node)
local prevNode
prevNode = searchNode(node)
node = list(prevNode, LINK)
print list(node, DATO);
print
end sub
 
 
sub traverseList()
local i
for i = 1 to countNodes
printNode(i)
next
end sub
 
 
insertNode(1, 1000, true)
insertNode(1, 2000, true)
insertNode(1, 3000, true)
 
traverseList()
 
removeNode(2)
 
print
traverseList()
</syntaxhighlight>
{{out}}
<pre>1000
3000
2000
 
1000
2000
---Program done, press RETURN---</pre>
 
=={{header|Zig}}==
Using the <code>LinkedList</code> struct definition from [[Singly-Linked List (element)#Zig|Singly-Linked List (element)]]
 
<syntaxhighlight lang="zig">const std = @import("std");
 
pub fn main() anyerror!void {
var l1 = LinkedList(i32).init();
 
try l1.add(1);
try l1.add(2);
try l1.add(4);
try l1.add(3);
 
var h = l1.head;
 
while (h) |head| : (h = head.next) {
std.log.info("> {}", .{ head.value });
}
}</syntaxhighlight>
 
{{out}}
 
<pre>
info: > 1
info: > 2
info: > 4
info: > 3
</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">foreach n in (List(1,2,3) {...}
List(1,2,3).pump(...) // traverse and munge elements, generalized apply/map
List(1,2,3).filter(...)
Line 1,390 ⟶ 2,359:
List(1,2,3).reverse()
List(1,2,3).concat()
List(1,2,3).shuffle()</langsyntaxhighlight>
9,476

edits