Singly-linked list/Element definition: Difference between revisions

m
(→‎{{header|Perl 6}}: mention pitfalls of Pair, and show custom type example)
m (→‎{{header|Wren}}: Minor tidy)
 
(40 intermediate revisions by 24 users not shown)
Line 2:
 
{{Template:See also lists}}
 
=={{header|360 Assembly}}==
The program uses DSECT and USING pseudo instruction to define a node.
<langsyntaxhighlight lang="360asm">* Singly-linked list/Element definition 07/02/2017
LISTSINA CSECT
USING LISTSINA,R13 base register
Line 90 ⟶ 91:
NEXT DS A
YREGS
END LISTSINA</langsyntaxhighlight>
{{out}}
<pre>
Line 97 ⟶ 98:
C
</pre>
 
=={{header|6502 Assembly}}==
A linked list entry can be created by writing its value and the pointer to the next one to RAM. It should be noted that without some form of dynamic memory allocation, a linked list is not easy to use.
 
<syntaxhighlight lang="6502asm">;create a node at address $0020, and another node at address $0040.
;The first node has a value of #$77, the second, #$99.
;create first node
LDA #$77
STA $20
LDA #$40
STA $21
LDA #$00
STA $22
 
;create second node
LDA #$99
STA $40
LDA #$FF ;use $FFFF as the null pointer since the only thing that can be at address $FFFF is the high byte of the IRQ routine.
STA $41
STA $42 </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 defList.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"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
lList1: .skip llist_fin * NBELEMENTS // list memory place
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main:
ldr x0,qAdrlList1
mov x1,#0
str x1,[x0,#llist_next]
ldr x0,qAdrszMessInitListe
bl affichageMess
 
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
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
 
=={{header|ACL2}}==
The built in pair type, <code>cons</code>, is sufficient for defining a linked list. ACL2 does not have mutable variables, so functions must instead return a copy of the original list.
 
<langsyntaxhighlight Lisplang="lisp">(let ((elem 8)
(next (list 6 7 5 3 0 9)))
(cons elem next))</langsyntaxhighlight>
 
Output:
<pre>(8 6 7 5 3 0 9)</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">DEFINE PTR="CARD"
 
TYPE ListNode=[
BYTE data
PTR nxt]</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Singly-linked_list_element_definition.png Screenshot from Atari 8-bit computer]
 
=={{header|ActionScript}}==
<langsyntaxhighlight ActionScriptlang="actionscript">package
{
public class Node
Line 121 ⟶ 213:
}
}
}</langsyntaxhighlight>
 
=={{header|Ada}}==
 
<langsyntaxhighlight lang="ada">type Link;
type Link_Access is access Link;
type Link is record
Next : Link_Access := null;
Data : Integer;
end record;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 135 ⟶ 228:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-2.7 algol68g-2.7].}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
'''File: prelude/single_link.a68'''<langsyntaxhighlight lang="algol68"># -*- coding: utf-8 -*- #
CO REQUIRES:
MODE OBJVALUE = ~ # Mode/type of actual obj to be stacked #
Line 149 ⟶ 242:
 
PROC obj nextlink free = (REF OBJNEXTLINK free)VOID:
next OF free := obj stack empty # give the garbage collector a BIG hint #</langsyntaxhighlight>'''See also:''' [[Stack#ALGOL_68|Stack]]
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw"> % record type to hold a singly linked list of integers %
record ListI ( integer iValue; reference(ListI) next );
 
Line 159 ⟶ 252:
 
% create a list of integers %
head := ListI( 1701, ListI( 9000, ListI( 42, ListI( 90210, null ) ) ) );</langsyntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program defList.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"
 
/* UnInitialized data */
.bss
lList1: .skip llist_fin * NBELEMENTS @ list memory place
 
/* code section */
.text
.global main
main:
ldr r0,iAdrlList1
mov r1,#0
str r1,[r0,#llist_next]
ldr r0,iAdrszMessInitListe
bl affichageMess
 
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
/******************************************************************/
/* 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
</syntaxhighlight>
 
=={{header|ATS}}==
 
<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 _ => ()</syntaxhighlight>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">element = 5 ; data
element_next = element2 ; link to next element</langsyntaxhighlight>
 
=={{header|AWK}}==
Line 169 ⟶ 357:
Awk only has global associative arrays, which will be used for the list. Numerical indexes into the array will serve as node pointers. A list element will have the next node pointer separated from the value by the pre-defined SUBSEP value. A function will be used to access a node's next node pointer or value given a node pointer (array index). The first array element will serve as the list head.
 
<langsyntaxhighlight lang="awk">
BEGIN {
NIL = 0
Line 193 ⟶ 381:
return linkAndValue[part]
}
</syntaxhighlight>
</lang>
 
=={{header|Axe}}==
<langsyntaxhighlight lang="axe">Lbl LINK
r₂→{r₁}ʳ
0→{r₁+2}ʳ
Line 208 ⟶ 396:
Lbl VALUE
{r₁}ʳ
Return</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> DIM node{pNext%, iData%}
</syntaxhighlight>
</lang>
 
=={{header|Bracmat}}==
Data mutation is not Bracmatish, but it can be done. Here is a datastructure for a mutable data value and for a mutable reference.
<langsyntaxhighlight lang="bracmat">link =
(next=)
(data=)</langsyntaxhighlight>
Example of use:
<langsyntaxhighlight lang="bracmat"> new$link:?link1
& new$link:?link2
& first thing:?(link1..data)
& secundus:?(link2..data)
& '$link2:(=?(link1..next))
& !(link1..next..data)</langsyntaxhighlight>
The last line returns
<pre>secundus</pre>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">struct link {
struct link *next;
int data;
};</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
 
<syntaxhighlight lang="csharp">class LinkedListNode
{
public int Value { get; set; }
public LinkedListNode Next { get; set; }
 
// A constructor is not necessary, but could be useful.
public Link(int value, LinkedListNode next = null)
{
Item = value;
Next = next;
}
}</syntaxhighlight>
 
A generic version:
<syntaxhighlight lang="csharp">class LinkedListNode<T>
{
public T Value { get; set; }
public LinkedListNode Next { get; set; }
 
public Link(T value, LinkedListNode next = null)
{
Item = value;
Next = next;
}
}</syntaxhighlight>
 
The most C-like possible version is basically C.
<syntaxhighlight lang="csharp">unsafe struct link {
public link* next;
public int data;
};</syntaxhighlight>
 
=={{header|C++}}==
Line 240 ⟶ 463:
The simplest C++ version looks basically like the C version:
 
<langsyntaxhighlight lang="cpp">struct link
{
link* next;
int data;
};</langsyntaxhighlight>
 
Initialization of links on the heap can be simplified by adding a constructor:
 
<langsyntaxhighlight lang="cpp">struct link
{
link* next;
int data;
link(int a_data, link* a_next = 0): next(a_next), data(a_data) {}
};</langsyntaxhighlight>
 
With this constructor, new nodes can be initialized directly at allocation; e.g. the following code creates a complete list with just one statement:
 
<langsyntaxhighlight lang="cpp"> link* small_primes = new link(2, new link(3, new link(5, new link(7))));</langsyntaxhighlight>
 
However, C++ also allows to make it generic on the data type (e.g. if you need large numbers, you might want to use a larger type than int, e.g. long on 64-bit platforms, long long on compilers that support it, or even a bigint class).
 
<langsyntaxhighlight lang="cpp">template<typename T> struct link
{
link* next;
T data;
link(T a_data, link* a_next = 0): next(a_next), data(a_data) {}
};</langsyntaxhighlight>
 
Note that the generic version works for any type, not only integral types.
 
=={{header|C sharp|C#Clean}}==
<syntaxhighlight lang="clean">import StdMaybe
<lang csharp>class Link
{
public int Item { get; set; }
public Link Next { get; set; }
 
:: Link t = { next :: Maybe (Link t), data :: t }</syntaxhighlight>
//A constructor is not neccessary, but could be useful
public Link(int item, Link next = null) {
Item = item;
Next = next;
}
}</lang>
 
=={{header|Clojure}}==
As with other LISPs, this is built in. Clojure provides a nice abstraction of lists with its use of: [http://clojure.org/sequences sequences] (also called seqs).
 
<langsyntaxhighlight lang="clojure">(cons 1 (cons 2 (cons 3 nil))) ; =>(1 2 3)</langsyntaxhighlight>
 
Note: this is an immutable data structure. With cons you are '''cons'''tructing a new seq.
Line 294 ⟶ 509:
The built-in <code>cons</code> type is used to construct linked lists. Using another type would be unidiomatic and inefficient.
 
<langsyntaxhighlight lang="lisp">(cons 1 (cons 2 (cons 3 nil)) => (1 2 3)</langsyntaxhighlight>
 
=={{header|Clean}}==
<lang clean>import StdMaybe
 
:: Link t = { next :: Maybe (Link t), data :: t }</lang>
 
=={{header|D}}==
Generic template-based node element.
 
<langsyntaxhighlight lang="d">struct SLinkedNode(T) {
T data;
typeof(this)* next;
Line 312 ⟶ 522:
alias SLinkedNode!int N;
N* n = new N(10);
}</langsyntaxhighlight>
Also the Phobos library contains a singly-linked list, std.container.SList. Tango contains tango.util.collection.LinkSeq.
 
Line 319 ⟶ 529:
A simple one way list. I use a generic pointer for the data that way it can point to any structure, individual variable or whatever. Note that in Standard Pascal, there are no generic pointers, therefore one has to settle for a specific data type there.
 
<langsyntaxhighlight lang="delphi">Type
pOneWayList = ^OneWayList;
OneWayList = record
pData : pointer ;
Next : pOneWayList ;
end;</langsyntaxhighlight>
 
=={{header|Diego}}==
<syntaxhighlight lang="diego">use_namespace(rosettacode)_me();
 
add_struct(link)_arg({link},next,{int},data);
 
add_link(primeNumbers)_arg([],2)_link()_arg([],3)_link()_arg([],5)_link()_arg(null,7);
 
reset_namespace[];</syntaxhighlight>
 
=={{header|E}}==
 
<langsyntaxhighlight lang="e">interface LinkedList guards LinkedListStamp {}
def empty implements LinkedListStamp {
to null() { return true }
Line 340 ⟶ 559:
}
return link
}</langsyntaxhighlight>
 
=={{header|Elena}}==
ELENA 6.x
<lang elena>class Link
<syntaxhighlight lang="elena">class Link
{
T<int> prop Item :: _item.prop;
T<Link> prop Next :: _next.prop;
constructor new(int item, Link next)
[{
_itemItem := item.;
_nextNext := next.
]}
}</langsyntaxhighlight>
 
=={{header|Erlang}}==
Lists are builtin, but Erlang is single assignment. Here we need mutable link to next element. Mutable in Erlang usually means a process, so:
<syntaxhighlight lang="erlang">
<lang Erlang>
new( Data ) -> erlang:spawn( fun() -> loop( Data, nonext ) end ).
</syntaxhighlight>
</lang>
For the whole module see [[Singly-linked_list/Element_insertion]]
 
=={{header|Factor}}==
<syntaxhighlight lang="text">TUPLE: linked-list data next ;
 
: <linked-list> ( data -- linked-list )
linked-list new swap >>data ;</langsyntaxhighlight>
 
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
class Node
{
Line 381 ⟶ 602:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Forth}}==
Line 387 ⟶ 608:
Idiomatically,
 
<langsyntaxhighlight lang="forth">0 value numbers
: push ( n -- )
here swap numbers , , to numbers ;</langsyntaxhighlight>
 
NUMBERS is the head of the list, initially nil (= 0); PUSH adds an element to the list; list cells have the structure {Link,Number}. Speaking generally, Number can be anything and list cells can be as long as desired (e.g., {Link,N1,N2} or {Link,Count,"a very long string"}), but the link is always first - or rather, a link always points to the next link, so that NEXT-LIST-CELL is simply fetch (@). Some operations:
 
<langsyntaxhighlight lang="forth">: length ( list -- u )
0 swap begin dup while 1 under+ @ repeat drop ;
 
Line 400 ⟶ 621:
 
: .numbers ( list -- )
begin dup while dup head . @ repeat drop ;</langsyntaxhighlight>
 
Higher-order programming, simple continuations, and immediate words can pull out the parallel code of LENGTH and .NUMBERS . Anonymous and dynamically allocated lists are as straightforward.
Line 406 ⟶ 627:
=={{header|Fortran}}==
In ISO Fortran 95 or later:
<langsyntaxhighlight lang="fortran">type node
real :: data
type( node ), pointer :: next => null()
Line 413 ⟶ 634:
!. . . .
!
type( node ) :: head</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">type ll_int
n as integer
nxt as ll_int ptr
end type</syntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">type Ele struct {
Data interface{}
Next *Ele
Line 433 ⟶ 660:
func (e *Ele) String() string {
return fmt.Sprintf("Ele: %v", e.Data)
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">class ListNode {
Object payload
ListNode next
String toString() { "${payload} -> ${next}" }
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">def n1 = new ListNode(payload:25)
n1.next = new ListNode(payload:88)
 
println n1</langsyntaxhighlight>
 
Output:
Line 458 ⟶ 685:
An equivalent declaration for such a list type without the special syntax would look like this:
 
<langsyntaxhighlight lang="haskell"> data List a = Nil | Cons a (List a)</langsyntaxhighlight>
 
A declaration like the one required in the task, with an integer as element type and a mutable link, would be
 
<langsyntaxhighlight lang="haskell"> data IntList s = Nil | Cons Integer (STRef s (IntList s))</langsyntaxhighlight>
 
but that would be really awkward to use.
Line 470 ⟶ 697:
The Icon version works in both Icon and Unicon. Unicon also permits a class-based definition.
 
=== {{header|Icon}} ===
 
<syntaxhighlight lang="icon">
<lang Icon>
record Node (value, successor)
</syntaxhighlight>
</lang>
 
=== {{header|Unicon}} ===
 
<syntaxhighlight lang="unicon">
<lang Unicon>
class Node (value, successor)
initially (value, successor)
Line 484 ⟶ 711:
self.successor := successor
end
</syntaxhighlight>
</lang>
 
With either the record or the class definition, new linked lists are easily created and manipulated:
 
<syntaxhighlight lang="icon">
<lang Icon>
procedure main ()
n := Node(1, Node (2))
Line 494 ⟶ 721:
write (n.successor.value)
end
</syntaxhighlight>
</lang>
 
=={{header|J}}==
Line 502 ⟶ 729:
However, for illustrative purposes:
 
<langsyntaxhighlight Jlang="j">list=: 0 2$0
list</langsyntaxhighlight>
 
This creates and then displays an empty list, with zero elements. The first number in an item is (supposed to be) the index of the next element of the list (_ for the final element of the list). The second number in an item is the numeric value stored in that list item. The list is named and names are mutable in J which means links are mutable.
Line 509 ⟶ 736:
To create such a list with one element which contains number 42, we can do the following:
 
<langsyntaxhighlight Jlang="j"> list=: ,: _ 42
list
_ 42</langsyntaxhighlight>
 
Now list contains one item, with index of the next item and value.
Line 517 ⟶ 744:
Note: this solution exploits the fact that, in this numeric case, data types for index and for node content are the same. If we need to store, for example, strings in the nodes, we should do something different, for example:
 
<langsyntaxhighlight Jlang="j"> list=: 0 2$a: NB. creates list with 0 items
list
list=: ,: (<_) , <'some text' NB. creates list with 1 item
Line 523 ⟶ 750:
+-+---------+
|_|some text|
+-+---------+</langsyntaxhighlight>
 
=={{header|Java}}==
Line 529 ⟶ 756:
The simplest Java version looks basically like the C++ version:
 
<langsyntaxhighlight lang="java">class Link
{
Link next;
int data;
}</langsyntaxhighlight>
 
Initialization of links on the heap can be simplified by adding a constructor:
 
<langsyntaxhighlight lang="java">class Link
{
Link next;
int data;
Link(int a_data, Link a_next) { next = a_next; data = a_data; }
}</langsyntaxhighlight>
 
With this constructor, new nodes can be initialized directly at allocation; e.g. the following code creates a complete list with just one statement:
 
<langsyntaxhighlight lang="java"> Link small_primes = new Link(2, new Link(3, new Link(5, new Link(7, null))));</langsyntaxhighlight>
 
{{works with|Java|1.5+}}
However, Java also allows to make it generic on the data type. This will only work on reference types, not primitive types like int or float (wrapper classes like Integer and Float are available).
 
<langsyntaxhighlight lang="java">class Link<T>
{
Link<T> next;
T data;
Link(T a_data, Link<T> a_next) { next = a_next; data = a_data; }
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">function LinkedList(value, next) {
this._value = value;
this._next = next;
Line 588 ⟶ 815:
}
 
var head = createLinkedListFromArray([10,20,30,40]);</langsyntaxhighlight>
 
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
 
In this entry, we envision a canonical mapping of SLLs to JSON objects as follows:
* the empty SLL is represented by `{"next": null}`
* a non-empty SLL is represented by an object of the form:
 
{"item": $item, "next": $next}
 
where $next is the canonical representative of a SLL, and $item may be any JSON value.
 
Examples:
* The empty SLL: { "next": null}
* A SLL holding the value 1 and no other: {"item": 1, "next": null}
<br>
Since it may be useful to allow non-canonical representatives of
SLLs, the following predicates adhere to the following principles:
* the empty SLL can be represented by any JSON object which does NOT have
a key named "item" and for which .next is `null`;
* non-empty SLLs can be represented by JSON objects having an "item" key and
for which .next is either `null` or a representative of a SLL.
 
Note that according to these principles, the JSON value `null` does
not represent a SLL, and JSON representatives of SLLs may have additional keys.
<syntaxhighlight lang="jq">def is_empty_singly_linked_list:
type == "object" and .next == null and (has("item")|not);
 
def is_singly_linked_list:
is_empty_singly_linked_list or
(type == "object"
and has("item")
and (.next | ((. == null) or is_singly_linked_list)));
 
# Test for equality without checking for validity:
def equal_singly_linked_lists($x; $y):
($x|is_empty_singly_linked_list) as $xempty
| if $xempty then ($y|is_empty_singly_linked_list)
elif ($y|is_empty_singly_linked_list)
then $xempty
else ($x.item) == ($y.item)
and equal_singly_linked_lists($x.next; $y.next)
end;
 
# insert $x into the front of the SLL
def insert($x):
if is_empty_singly_linked_list then {item: $x, next: null}
else .next |= new($x; .)
end;
</syntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">abstract type AbstractNode{T} end
 
struct EmptyNode{T} <: AbstractNode{T} end
Line 651 ⟶ 929:
pop!(lst) # 3
pop!(lst) # 2
pop!(lst) # 1</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
class Node<T: Number>(var data: T, var next: Node<T>? = null) {
Line 671 ⟶ 949:
val n = Node(1, Node(2, Node(3)))
println(n)
}</langsyntaxhighlight>
 
{{out}}
Line 677 ⟶ 955:
1 -> 2 -> 3
</pre>
 
=={{header|Lang}}==
<syntaxhighlight lang="lang">
&Node = {
$next
$data
}
</syntaxhighlight>
 
=={{header|Logo}}==
As with other list-based languages, simple lists are represented easily in Logo.
 
<langsyntaxhighlight lang="logo">fput item list ; add item to the head of a list
 
first list ; get the data
butfirst list ; get the remainder
bf list ; contraction for "butfirst"</langsyntaxhighlight>
 
These return modified lists, but you can also destructively modify lists. These are normally not used because you might accidentally create cycles in the list.
 
<langsyntaxhighlight lang="logo">.setfirst list value
.setbf list remainder</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Append[{}, x]
-> {x}</langsyntaxhighlight>
 
=={{header|MiniScript}}==
Implementing linked lists in MiniScript is an academic exercise. For practical applications, use the built-in list type.
<syntaxhighlight lang="miniscript">
Node = {"item": null, "next": null}
Node.init = function(item)
node = new Node
node.item = item
return node
end function
 
LinkedList = {"head": null, "tail": null}
LinkedList.append = function(item)
newNode = Node.init(item)
if self.head == null then
self.head = newNode
self.tail = self.head
else
self.tail.next = newNode
self.tail = self.tail.next
end if
end function
 
LinkedList.insert = function(aftItem, item)
newNode = Node.init(item)
cursor = self.head
while cursor.item != aftItem
print cursor.item
cursor = cursor.next
end while
newNode.next = cursor.next
cursor.next = newNode
end function
 
LinkedList.traverse = function
cursor = self.head
while cursor != null
// do stuff
print cursor.item
cursor = cursor.next
end while
end function
 
test = new LinkedList
test.append("A")
test.append("B")
test.insert("A","C")
 
test.traverse
</syntaxhighlight>
 
=={{header|Modula-2}}==
 
<langsyntaxhighlight lang="modula2">TYPE
Link = POINTER TO LinkRcd;
LinkRcd = RECORD
Next: Link;
Data: INTEGER
END;</langsyntaxhighlight>
 
=={{header|Modula-3}}==
<langsyntaxhighlight lang="modula3">TYPE
Link = REF LinkRcd;
LinkRcd = RECORD
Next: Link;
Data: INTEGER
END;</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
The simplest version in Nanoquery is similar to the C version:
<syntaxhighlight lang="nanoquery">class link
declare data
declare next
end</syntaxhighlight>
 
Like Java, it is possible to add a constructor that allows us to set the values on initialization.
<syntaxhighlight lang="nanoquery">class link
declare data
declare next
 
def link(data, next)
this.data = data
this.next = next
end
end</syntaxhighlight>
 
This allows us to define an entire list in a single (albeit confusing) line of source.
<syntaxhighlight lang="nanoquery">linkedlist = new(link, 1, new(link, 2, new(link, 3, new(link, 4, null))))</syntaxhighlight>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">
<lang nim>type Node[T] = ref object
import std/strutils # for join
next: Node[T]
 
data: T
type
Node[T] = ref object
next: Node[T]
data: T
 
SinglyLinkedList[T] = object
head, tail: Node[T]
 
proc newNode[T](data: T): Node[T] =
Node[T](data: data)
 
proc append[T](list: var SinglyLinkedList[T]; node: Node[T]) =
var a = newNode 12
if list.head.isNil:
var b = newNode 13
list.head = node
var c = newNode 14</lang>
list.tail = node
else:
list.tail.next = node
list.tail = node
 
proc append[T](list: var SinglyLinkedList[T]; data: T) =
list.append newNode(data)
 
proc prepend[T](list: var SinglyLinkedList[T]; node: Node[T]) =
if list.head.isNil:
list.head = node
list.tail = node
else:
node.next = list.head
list.head = node
 
proc prepend[T](list: var SinglyLinkedList[T]; data: T) =
list.prepend newNode(data)
 
proc `$`[T](list: SinglyLinkedList[T]): string =
var s: seq[T]
var n = list.head
while not n.isNil:
s.add n.data
n = n.next
result = s.join(" → ")
 
var list: SinglyLinkedList[int]
 
for i in 1..5: list.append(i)
for i in 6..10: list.prepend(i)
echo "List: ", $list
</syntaxhighlight>
 
{{out}}
<pre>List: 10 → 9 → 8 → 7 → 6 → 1 → 2 → 3 → 4 → 5</pre>
 
=={{header|Objective-C}}==
 
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
@interface RCListElement<T> : NSObject
Line 759 ⟶ 1,159:
datum = d;
}
@end</langsyntaxhighlight>
 
=={{header|OCaml}}==
Line 767 ⟶ 1,167:
An equivalent declaration for such a list type without the special syntax would look like this:
 
<langsyntaxhighlight lang="ocaml"> type 'a list = Nil | Cons of 'a * 'a list</langsyntaxhighlight>
 
A declaration like the one required in the task, with an integer as element type and a mutable link, would be
 
<langsyntaxhighlight lang="ocaml"> type int_list = Nil | Cons of int * int_list ref</langsyntaxhighlight>
 
but that would be really awkward to use.
 
=={{header|Odin}}==
 
<syntaxhighlight lang="odin">Node :: struct {
data: rune,
next: ^Node,
}</syntaxhighlight>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">Collection Class new: LinkedList(data, mutable next)</langsyntaxhighlight>
 
=={{header|ooRexx}}==
 
The simplest ooRexx version is similar in form to the Java or C++ versions:
<syntaxhighlight lang="oorexx">
<lang ooRexx>
list = .linkedlist~new
index = list~insert("abc") -- insert a first item, keeping the index
Line 918 ⟶ 1,325:
 
 
</syntaxhighlight>
</lang>
 
A link element can hold a reference to any ooRexx object.
Line 924 ⟶ 1,331:
=={{header|Pascal}}==
 
<langsyntaxhighlight lang="pascal">type
PLink = ^TLink;
TLink = record
FNext: PLink;
FData: integer;
end;</langsyntaxhighlight>
 
=={{header|Perl}}==
Line 935 ⟶ 1,342:
 
However, if all you got is an algorithm in a foreign language, you can use references to accomplish the translation.
<langsyntaxhighlight lang="perl">my %node = (
data => 'say what',
next => \%foo_node,
);
$node{next} = \%bar_node; # mutable</langsyntaxhighlight>
=={{header|Perl 6}}==
 
====With <tt>Pair</tt>====
 
A <tt>Pair</tt> (constructed with the <code>=></code> operator) can be treated as a cons cell, and thus used to build a linked lists:
 
<lang perl6>my $elem = 42 => $nextelem;</lang>
 
However, because this is not the primary purpose of the <tt>Pair</tt> type, it suffers from the following limitations:
 
* The naming of <tt>Pair</tt>'s accessor methods is not idiomatic for this use case (<code>.key</code> for the cell's value, and <code>.value</code> for the link to the next cell).
* A <tt>Pair</tt> (unlike an <tt>Array</tt>) does not automatically wrap its keys/values in item containers &ndash; so each cell of the list will be immutable once created, making element insertion/deletion impossible (except inserting at the front).
* It provides no built-in convenience methods for iterating/modifying/transforming such a list.
 
====With custom type====
 
For more flexibility, one would create a custom type:
 
<lang perl6>class Cell {
has $.value is rw;
has Cell $.next is rw;
# ...convenience methods here...
}
 
sub cons ($value, $next) { Cell.new(:$value, :$next) }
 
my $list = cons 10, (cons 20, (cons 30, Nil));</lang>
 
=={{header|Phix}}==
In Phix, types are used for validation and debugging rather than specification purposes. For extensive run-time checking you could use something like
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>enum NEXT,DATA
<span style="color: #008080;">enum</span> <span style="color: #000000;">NEXT</span><span style="color: #0000FF;">,</span><span style="color: #000000;">DATA</span>
type slnode(object x)
<span style="color: #008080;">type</span> <span style="color: #000000;">slnode</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">)</span>
return (sequence(x) and length(x)=DATA and myotherudt(x[DATA]) and integer(x[NEXT])
<span style="color: #008080;">return</span> <span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">and</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">DATA</span> <span style="color: #008080;">and</span> <span style="color: #000000;">myotherudt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">[</span><span style="color: #000000;">DATA</span><span style="color: #0000FF;">])</span> <span style="color: #008080;">and</span> <span style="color: #004080;">integer</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">[</span><span style="color: #000000;">NEXT</span><span style="color: #0000FF;">])</span>
end type</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">type</span>
<!--</syntaxhighlight>-->
But more often you would just use the builtin sequences. It is worth noting that while "node lists", such as
{{2},{'A',3},{'B',4},{'C',0}} are one way to hold a linked list (with the first element a dummy header),
Line 1,000 ⟶ 1,381:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
declare 1 node based (p),
2 value fixed,
2 link pointer;
</syntaxhighlight>
</lang>
 
=={{header|Pop11}}==
Line 1,010 ⟶ 1,391:
List are built in into Pop11, so normally on would just use them:
 
<langsyntaxhighlight lang="pop11">;;; Use shorthand syntax to create list.
lvars l1 = [1 2 three 'four'];
;;; Allocate a single list node, with value field 1 and the link field
Line 1,024 ⟶ 1,405:
l1 -> back(l2);
;;; Print l2
l2 =></langsyntaxhighlight>
 
If however one wants to definite equivalent user-defined type, one can do this:
 
<langsyntaxhighlight lang="pop11">uses objectclass;
define :class ListNode;
slot value = [];
Line 1,043 ⟶ 1,424:
;;; of l1
consListNode(2, []) -> next(l1);
l1 =></langsyntaxhighlight>
 
=={{header|PureBasic}}==
 
<langsyntaxhighlight PureBasiclang="purebasic">Structure MyData
*next.MyData
Value.i
EndStructure</langsyntaxhighlight>
 
=={{header|Python}}==
Line 1,056 ⟶ 1,437:
The Node class implements also iteration for more Pythonic iteration over linked lists.
 
<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,082 ⟶ 1,463:
while cursor:
yield cursor.value
cursor = cursor.next</langsyntaxhighlight>
 
'''Note:''' As explained in this class' docstring implementing linked lists and nodes in Python is an utterly pointless academic exercise. It may give on the flavor of the elements that would be necessary in some other programming languages (''e.g.'' using Python as "executable psuedo-code"). Adding methods for finding, counting, removing and inserting elements is left as an academic exercise to the reader. For any practical application use the built-in ''list()'' or ''dict()'' types as appropriate.
Line 1,090 ⟶ 1,471:
Unlike other Lisp dialects, Racket's <tt>cons</tt> cells are immutable, so they cannot be used to satisfy this task. However, Racket also includes mutable pairs which are still the same old mutable singly-linked lists.
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
(mcons 1 (mcons 2 (mcons 3 '()))) ; a mutable list
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
 
====With <tt>Pair</tt>====
 
A <tt>Pair</tt> (constructed with the <code>=></code> operator) can be treated as a cons cell, and thus used to build a linked lists:
 
<syntaxhighlight lang="raku" line>my $elem = 42 => $nextelem;</syntaxhighlight>
 
However, because this is not the primary purpose of the <tt>Pair</tt> type, it suffers from the following limitations:
 
* The naming of <tt>Pair</tt>'s accessor methods is not idiomatic for this use case (<code>.key</code> for the cell's value, and <code>.value</code> for the link to the next cell).
* A <tt>Pair</tt> (unlike an <tt>Array</tt>) does not automatically wrap its keys/values in item containers &ndash; so each cell of the list will be immutable once created, making element insertion/deletion impossible (except inserting at the front).
* It provides no built-in convenience methods for iterating/modifying/transforming such a list.
 
====With custom type====
 
For more flexibility, one would create a custom type:
 
<syntaxhighlight lang="raku" line>class Cell {
has $.value is rw;
has Cell $.next is rw;
# ...convenience methods here...
}
 
sub cons ($value, $next) { Cell.new(:$value, :$next) }
 
my $list = cons 10, (cons 20, (cons 30, Nil));</syntaxhighlight>
 
=={{header|REXX}}==
The REXX language doesn't have any native linked lists, but they can be created easily.
<br>The values of a REXX linked list can be anything (nulls, character strings, including any type/kind of number, of course).
<langsyntaxhighlight lang="rexx">/*REXX program demonstrates how to create and show a single-linked list.*/
@.=0 /*define a null linked list. */
call set@ 3 /*linked list: 12 Proth Primes. */
Line 1,135 ⟶ 1,546:
@..y=n /*set a locator pointer to self. */
@.max_width=max(@.max_width,length(y)) /*set maximum width of any value.*/
return /*return to invoker of this sub. */</langsyntaxhighlight>
'''output'''
<pre>
Line 1,156 ⟶ 1,567:
=={{header|Ruby}}==
 
<langsyntaxhighlight lang="ruby">class ListNode
attr_accessor :value, :succ
 
Line 1,183 ⟶ 1,594:
end
 
list = ListNode.from_array([1,2,3,4])</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<syntaxhighlight lang="runbasic">data = 10
link = 10
dim node{data,link} </syntaxhighlight>
 
=={{header|Rust}}==
Rust's <code>Option<T></code> type make the definition of a singly-linked list trivial. The use of <code>Box<T></code> (an owned pointer) is necessary because it has a known size, thus making sure the struct that contains it can have a finite size.
<langsyntaxhighlight Rustlang="rust"> struct Node<T> {
elem: T,
next: Option<Box<Node<T>>>,
}</langsyntaxhighlight>
 
However, the above example would not be suitable for a library because, first and foremost, it is private by default but simply making it public would not allow for any encapsulation.
 
<langsyntaxhighlight Rustlang="rust">type Link<T> = Option<Box<Node<T>>>; // Type alias
pub struct List<T> { // User-facing interface for list
head: Link<T>,
Line 1,209 ⟶ 1,625:
List { head: None }
// Add other methods here
}</langsyntaxhighlight>
 
Then a separate program could utilize the basic implementation above like so:
<langsyntaxhighlight lang="rust">extern crate LinkedList; // Name is arbitrary here
 
use LinkedList::List;
Line 1,219 ⟶ 1,635:
let list = List::new();
// Do stuff
}</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<lang runbasic>data = 10
link = 10
dim node{data,link} </lang>
 
=={{header|Scala}}==
Immutable lists that you can use with pattern matching.
 
<langsyntaxhighlight lang="scala">
sealed trait List[+A]
case class Cons[+A](head: A, tail: List[A]) extends List[A]
Line 1,238 ⟶ 1,649:
if (as.isEmpty) Nil else Cons(as.head, apply(as.tail: _*))
}
</syntaxhighlight>
</lang>
 
Basic usage
 
<langsyntaxhighlight lang="scala">
def main(args: Array[String]): Unit = {
val words = List("Rosetta", "Code", "Scala", "Example")
}
</syntaxhighlight>
</lang>
 
=={{header|Scheme}}==
 
Scheme, like other Lisp dialects, has extensive support for singly-linked lists. The element of such a list is known as a ''cons-pair'', because you use the <tt>cons</tt> function to construct it:
<syntaxhighlight lang ="scheme">(cons value next)</langsyntaxhighlight>
 
The value and next-link parts of the pair can be deconstructed using the <tt>car</tt> and <tt>cdr</tt> functions, respectively:
<langsyntaxhighlight lang="scheme">(car my-list) ; returns the first element of the list
(cdr my-list) ; returns the remainder of the list</langsyntaxhighlight>
 
Each of these parts are mutable and can be set using the <tt>set-car!</tt> and <tt>set-cdr!</tt> functions, respectively:
<langsyntaxhighlight lang="scheme">(set-car! my-list new-elem)
(set-cdr! my-list new-next)</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var node = Hash.new(
data => 'say what',
next => foo_node,
);
 
node{:next} = bar_node; # mutable</langsyntaxhighlight>
 
 
=={{header|SSEM}}==
At the machine level, an element of a linked list can be represented using two successive words of storage where the first holds an item of data and the second holds either (a) the address where the next such pair of words will be found, or (b) a special <tt>NIL</tt> address indicating that we have reached the end of the list. Here is one way in which the list <tt>'(1 2 3)</tt> could be represented in SSEM code:
<langsyntaxhighlight lang="ssem">01000000000000000000000000000000 26. 2
01111000000000000000000000000000 27. 30
10000000000000000000000000000000 28. 1
01011000000000000000000000000000 29. 26
11000000000000000000000000000000 30. 3
00000000000000000000000000000000 31. 0</langsyntaxhighlight>
Notice that the physical location of the pairs in storage can vary arbitrarily, and that (in this implementation) <tt>NIL</tt> is represented by zero. For an example showing how this list can be accessed, see [[Singly-Linked List (traversal)#SSEM]].
 
Line 1,293 ⟶ 1,703:
Here we define two [https://www.stata.com/help.cgi?m2_struct structures]: one to hold a list item, another to hold the list [https://www.stata.com/help.cgi?m2_pointer pointers]: we store both the head and the tail, in order to be able to insert an element at both ends. An empty list has both head and tail set to NULL.
 
<langsyntaxhighlight lang="stata">struct item {
transmorphic scalar value
pointer(struct item scalar) scalar next
Line 1,300 ⟶ 1,710:
struct list {
pointer(struct item scalar) scalar head, tail
}</langsyntaxhighlight>
 
=== Test if empty ===
<langsyntaxhighlight lang="stata">real scalar list_empty(struct list scalar a) {
return(a.head == NULL)
}</langsyntaxhighlight>
 
Note that when a structure value is created, here for instance with <code>a = list()</code>, the elements are set to default values (zero real scalar, NULL pointer...). Hence, a newly created list is always empty.
Line 1,312 ⟶ 1,722:
We can insert an element either before head or after tail. We can also insert after a given list item, but we must make sure the tail pointer of the list is updated if necessary.
 
<langsyntaxhighlight lang="stata">void function list_insert(struct list scalar a, transmorphic scalar x) {
struct item scalar i
i.value = x
Line 1,347 ⟶ 1,757:
a.tail = &i
}
}</langsyntaxhighlight>
 
=== Traversal ===
Line 1,353 ⟶ 1,763:
Here are functions to compute the list length, and to print its elements. Here we assume list elements are either strings or real numbers, but one could write a more general function.
 
<langsyntaxhighlight lang="stata">real scalar list_length(struct list scalar a) {
real scalar n
pointer(struct item scalar) scalar p
Line 1,374 ⟶ 1,784:
}
}
}</langsyntaxhighlight>
 
=== Return nth item ===
The function returns a pointer to the nth list item. If there are not enough elements, NULL is returned.
 
<langsyntaxhighlight lang="stata">pointer(struct item scalar) scalar list_get(struct list scalar a,
real scalar n) {
Line 1,390 ⟶ 1,800:
}
return(p)
}</langsyntaxhighlight>
 
=== Remove and return first element ===
Line 1,396 ⟶ 1,806:
The following function "pops" the first element of the list. If the list is empty, Mata will throw an error.
 
<langsyntaxhighlight lang="stata">transmorphic scalar list_pop(struct list scalar a) {
transmorphic scalar x
if (a.head == NULL) {
Line 1,408 ⟶ 1,818:
}
return(x)
}</langsyntaxhighlight>
 
=== Remove and return nth element ===
 
<langsyntaxhighlight lang="stata">transmorphic scalar list_remove(struct list scalar a,
real scalar n) {
Line 1,448 ⟶ 1,858:
}
return(x)
}</langsyntaxhighlight>
 
=== Examples ===
Line 1,454 ⟶ 1,864:
Adding to the head:
 
<langsyntaxhighlight lang="stata">a = list()
list_insert(a, 10)
list_insert(a, 20)
list_insert(a, 30)
list_length(a)
list_show(a);</langsyntaxhighlight>
 
'''Output'''
Line 1,471 ⟶ 1,881:
Adding to the tail:
 
<langsyntaxhighlight lang="stata">a = list()
list_insert_end(a, 10)
list_insert_end(a, 20)
list_insert_end(a, 30)
list_length(a)
list_show(a);</langsyntaxhighlight>
 
'''Output'''
Line 1,488 ⟶ 1,898:
Adding after an element:
 
<langsyntaxhighlight lang="stata">list_insert_after(a, list_get(a, 2), 40)
list_show(a);</langsyntaxhighlight>
 
'''Output'''
Line 1,502 ⟶ 1,912:
Pop the first element:
 
<syntaxhighlight lang ="stata">list_pop(a)</langsyntaxhighlight>
 
'''Output'''
Line 1,512 ⟶ 1,922:
=== Linked-list task ===
 
<langsyntaxhighlight lang="stata">a = list()
list_insert_end(a, "A")
list_insert_end(a, "B")
list_insert_after(a, list_get(a, 1), "C")
list_show(a)</langsyntaxhighlight>
 
'''Output'''
Line 1,528 ⟶ 1,938:
=== Stack behavior ===
 
<langsyntaxhighlight lang="stata">a = list()
for (i = 1; i <= 4; i++) {
list_insert(a, i)
Line 1,534 ⟶ 1,944:
while (!list_empty(a)) {
printf("%f\n", list_pop(a))
}</langsyntaxhighlight>
 
'''Output'''
Line 1,547 ⟶ 1,957:
=== Queue behavior ===
 
<langsyntaxhighlight lang="stata">a = list()
for (i = 1; i <= 4; i++) {
list_insert_end(a, i)
Line 1,553 ⟶ 1,963:
while (!list_empty(a)) {
printf("%f\n", list_pop(a))
}</langsyntaxhighlight>
 
'''Output'''
Line 1,565 ⟶ 1,975:
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">class Node<T>{
var data: T? = nil
var next: Node? = nil
init(input: T){
data = input
next = nil
}
}
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
Line 1,579 ⟶ 1,989:
 
{{Works with|Tcl|8.6}} or {{libheader|TclOO}}
<langsyntaxhighlight lang="tcl">oo::class create List {
variable content next
constructor {value {list ""}} {
Line 1,603 ⟶ 2,013:
return $values
}
}</langsyntaxhighlight>
 
=={{header|Wren}}==
{{libheader|Wren-llist}}
The Node class in the above module is the element type for the LinkedList class which is a generic singly-linked list. The latter is implemented in such a way that the user does not need to deal directly with Node though for the purposes of the task we show below how instances of it can be created and manipulated.
<syntaxhighlight lang="wren">import "./llist" for Node
 
var n1 = Node.new(1)
var n2 = Node.new(2)
n1.next = n2
System.print(["node 1", "data = %(n1.data)", "next = %(n1.next)"])
System.print(["node 2", "data = %(n2.data)", "next = %(n2.next)"])</syntaxhighlight>
 
{{out}}
<pre>
[node 1, data = 1, next = 2]
[node 2, data = 2, next = null]
</pre>
 
=={{header|X86 Assembly}}==
------------------------------------------------------------------------------
This file will be included in the singly-linked list operation implementations
<langsyntaxhighlight lang="x86asm">
; x86_64 Linux NASM
; Linked_List_Definition.asm
Line 1,622 ⟶ 2,049:
 
%endif
</syntaxhighlight>
</lang>
------------------------------------------------------------------------------
 
{{works with|NASM}}
 
<langsyntaxhighlight lang="asm">
struct link
.next: resd 1
.data: resd 1
endstruc
</syntaxhighlight>
</lang>
Of course, ASM not natively having structures we can simply do..
<langsyntaxhighlight lang="asm">
link resb 16
</syntaxhighlight>
</lang>
Which would reserve 16 bytes(2 dwords). We could just simply think of it in the form of a structure.<br><br>
{{works with|MASM}}
<langsyntaxhighlight lang="asm">
link struct
next dd ?
data dd ?
link ends
</syntaxhighlight>
</lang>
{{works with|FASM}}
<langsyntaxhighlight lang="asm">struc link next,data
{
.next dd next
.data dd data
}</langsyntaxhighlight>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">includedef c:\cxplNode\codes Link, Data; \intrinsiclinked list 'code'element declarationsdefinition
int Node, List, N;
def IntSize=4; \number of bytes in an integer
def SizeIntSize =10 4; \number of nodesbytes in this linkedan listinteger
[List:= 0; \List is initially empty
int Link, List, Node;
[Linkfor N:= 0; 1 to 10 do \build linked list, starting at the end
[Node:= Reserve(IntSize*2); \get some memory to store Link and Data
for Node:= 0 to Size-1 do
Node(Link):= List;
[List:= Reserve(IntSize*2); \get some memory to hold link and data
Node(Data):= N*N; \insert example data
List(0):= Link;
List(1):= Node*Node; \insertList now points to newly examplecreated datanode
];
Link:= List; \Link now points to newly created node
];
Node:= List; \traverse the linked list
while Node # 0 do
repeat IntOut(0, Node(1)); CrLf(0); \display the example data
Node:=[IntOut(0, Node(0Data)); \movedisplay tothe nextexample nodedata
ChOut(0, ^ );
until Node=0; \end of the list
Node:= Node(Link); \move to next node
]</lang>
];
]</syntaxhighlight>
 
{{out}}
<pre>
100 81 64 49 36 25 16 9 4 1
</pre>
 
=={{header|Zig}}==
<syntaxhighlight lang="zig">const std = @import("std");
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = arena.allocator();
pub fn LinkedList(comptime Value: type) type {
return struct {
const This = @This();
const Node = struct {
value: Value,
next: ?*Node,
};
head: ?*Node,
tail: ?*Node,
pub fn init() This {
return LinkedList(Value) {
.head = null,
.tail = null,
};
}
pub fn add(this: *This, value: Value) !void {
var newNode = try allocator.create(Node);
newNode.* = .{ .value = value, .next = null };
if (this.tail) |tail| {
tail.next = newNode;
this.tail = newNode;
} else if (this.head) |head| {
head.next = newNode;
this.tail = newNode;
} else {
this.head = newNode;
}
}
};
}</syntaxhighlight>
 
=={{header|zkl}}==
Lists are a core element in zkl, both mutable and immutable. They are heterogeneous and can hold any object. They can be recursive.
<langsyntaxhighlight lang="zkl">List(1,"two",3.14); L(1,"two",3.14);
ROList(fcn{"foobar"}); T('+);</langsyntaxhighlight>
 
{{omit from|GUISS}}
9,476

edits