Doubly-linked list/Element definition: Difference between revisions

m
m (→‎{{header|Wren}}: Minor tidy)
 
(41 intermediate revisions by 24 users not shown)
Line 11:
{{Template:See also lists}}
<br><br>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">DEFINE PTR="CARD"
 
TYPE ListNode=[
BYTE data
PTR prv,nxt]</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Doubly-linked_list_element_definition.png Screenshot from Atari 8-bit computer]
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">type Link;
type Link_Access is access Link;
type Link is record
Line 19 ⟶ 28:
Prev : Link_Access := null;
Data : Integer;
end record;</langsyntaxhighlight>
Using generics, the specification might look like this:
<langsyntaxhighlight lang="ada">generic
type Element_Type is private;
package Linked_List is
Line 43 ⟶ 52:
Traversing : Boolean := False; -- True when in a traversal.
end record;
end Linked_List;</langsyntaxhighlight>
In Ada 2005 this example can be written without declaration of an access type:
<langsyntaxhighlight lang="ada">type Link is limited record
Next : not null access Link := Link'Unchecked_Access;
Prev : not null access Link := Link'Unchecked_Access;
Data : Integer;
end record;</langsyntaxhighlight>
Here the list element is created already pointing to itself, so that no further initialization is required. The type of the element is marked as ''limited'' indicating that such elements have referential semantics and cannot be copied.
 
Ada's standard container library includes a generic doubly linked list. The structure of the link element is private.
 
 
=={{header|ALGOL 68}}==
Line 59 ⟶ 67:
{{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/link.a68'''<langsyntaxhighlight lang="algol68"># -*- coding: utf-8 -*- #
CO REQUIRES:
MODE OBJVALUE = ~ # Mode/type of actual obj to be queued #
Line 73 ⟶ 81:
 
PROC obj link free = (REF OBJLINK free)VOID:
prev OF free := next OF free := obj queue empty # give the garbage collector a big hint #</langsyntaxhighlight>'''See also:''' [[Queue/Usage#ALGOL_68|Queue/Usage]]
 
=={{header|ALGOL W}}==
<syntaxhighlight lang="algolw"> % record type to hold an element of a doubly linked list of integers %
record DListIElement ( reference(DListIElement) prev
; integer iValue
; reference(DListIElement) next
);
% additional record types would be required for other element types %</syntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
 
/* ARM assembly Raspberry PI */
 
/* structure Node Doublylinked List*/
.struct 0
NDlist_next: @ next element
.struct NDlist_next + 4
NDlist_prev: @ previous element
.struct NDlist_prev + 4
NDlist_value: @ element value or key
.struct NDlist_value + 4
NDlist_fin:
</syntaxhighlight>
 
=={{header|AutoHotkey}}==
Line 79 ⟶ 112:
 
=={{header|Axe}}==
<langsyntaxhighlight lang="axe">Lbl LINK
r₂→{r₁}ʳ
0→{r₁+2}ʳ
Line 96 ⟶ 129:
Lbl VALUE
{r₁}ʳ
Return</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> DIM node{pPrev%, pNext%, iData%}
</syntaxhighlight>
</lang>
 
=={{header|Bracmat}}==
<syntaxhighlight lang="bracmat">link=(prev=) (next=) (data=)</syntaxhighlight>
 
=={{header|C}}==
It basically doesn't matter if we use the name link, node, Node or some other name. These are matters of taste and aesthetics. However, it is important that the C language is case-sensitive and that the namespace for structures is separate.
<lang c>struct link
<syntaxhighlight lang="c">struct Node
{
struct linkNode *next;
struct linkNode *prev;
void *data;
};</syntaxhighlight>
size_t type;
An alternative technique is to define a pointer type by typedef as shown below. The advantage here is that you do not have to write struct everywhere - assuming that you will most often need a pointer to a struct Node, not the structure itself.
};</lang>
<syntaxhighlight lang="c">
struct Node;
typedef struct Node* Node;
struct Node
{
Node next;
Node prev;
void* data;
};
</syntaxhighlight>
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">class Link
{
public int Item { get; set; }
public Link Prev { get; set; }
public Link Next { get; set; }
 
//A constructor is not neccessary, but could be useful
public Link(int item, Link prev = null, Link next = null) {
Item = item;
Prev = prev;
Next = next;
}
}</syntaxhighlight>
 
=={{header|C++}}==
C++ has doubly linked list class template in standard library. However actual list noded are treated as implementation detail and encapsulated inside list. If we were to reimplement list, then node could look like that:
<langsyntaxhighlight lang="cpp">template <typename T>
struct Node
{
Line 120 ⟶ 183:
Node* prev;
T data;
};</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<lang csharp>class Link
{
public int item;
public Link next;
public Link prev;
}</lang>
 
=={{header|Clojure}}==
Line 134 ⟶ 189:
This sort of mutable structure is not idiomatic in Clojure. [[../Definition#Clojure]] or a finger tree implementation would be better.
 
<langsyntaxhighlight Clojurelang="clojure">(defrecord Node [prev next data])
 
(defn new-node [prev next data]
(Node. (ref prev) (ref next) data))</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
 
<langsyntaxhighlight lang="lisp">(defstruct dlist head tail)
(defstruct dlink content prev next)</langsyntaxhighlight>
 
See the functions on the [[Doubly-Linked List]] page for the usage of these structures.
Line 148 ⟶ 203:
=={{header|D}}==
A default constructor is implicit:
<langsyntaxhighlight lang="d">struct Node(T) {
T data;
typeof(this)* prev, next;
Line 156 ⟶ 211:
alias N = Node!int;
N* n = new N(10);
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
<langsyntaxhighlight lang="d">struct Node(T) {
 
type
Line 171 ⟶ 226:
end;
 
}</langsyntaxhighlight>
 
=={{header|E}}==
Line 177 ⟶ 232:
This does no type-checking, under the assumption that it is being used by a containing doubly-linked list object which enforces that invariant along with others such as that <code>element.getNext().getPrev() == element</code>. See [[Doubly-Linked List#E]] for an actual implementation (which uses slightly more elaborate nodes than this).
 
<langsyntaxhighlight lang="e">def makeElement(var value, var next, var prev) {
def element {
to setValue(v) { value := v }
Line 190 ⟶ 245:
return element
}</langsyntaxhighlight>
 
=={{header|Erlang}}==
Using the code in [[Doubly-linked_list/Definition]] the element is defined by:
<syntaxhighlight lang="erlang">
<lang Erlang>
new( Data ) -> erlang:spawn( fun() -> loop( Data, noprevious, nonext ) end ).
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">
type 'a DLElm = {
mutable prev: 'a DLElm option
data: 'a
mutable next: 'a DLElm option
}
</syntaxhighlight>
 
=={{header|Factor}}==
<syntaxhighlight lang="factor">TUPLE: node data next prev ;</syntaxhighlight>
 
=={{header|Fortran}}==
In ISO Fortran 95 or later:
<langsyntaxhighlight lang="fortran">type node
real :: data
type(node), pointer :: next => null(), previous => null()
Line 207 ⟶ 274:
! . . . .
!
type( node ), target :: head</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">type node
nxt as node ptr
prv as node ptr
dat as any ptr 'points to any kind of data; user's responsibility
'to keep track of what's actually in it
end type</syntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">type dlNode struct {
string
next, prev *dlNode
}</langsyntaxhighlight>
Or, using the [http://golang.org/pkg/container/list/#Element container/list] package:
<langsyntaxhighlight lang="go">import "container/list"
 
var node list.Element
// and using: node.Next(), node.Prev(), node.Value</langsyntaxhighlight>
 
=={{header|Haskell}}==
Line 225 ⟶ 300:
Note that unlike naive pointer manipulation which could corrupt the doubly-linked list, updateLeft and updateRight will always yield a well-formed data structure.
 
<langsyntaxhighlight lang="haskell">
data DList a = Leaf | Node (DList a) a (DList a)
 
Line 239 ⟶ 314:
where current = Node l v next
next = updateRight nr new
</syntaxhighlight>
</lang>
 
==Icon and {{header|Unicon}}==
Line 245 ⟶ 320:
Uses Unicon classes.
 
<syntaxhighlight lang="unicon">
<lang Unicon>
class DoubleLink (value, prev_link, next_link)
initially (value, prev_link, next_link)
Line 252 ⟶ 327:
self.next_link := next_link
end
</syntaxhighlight>
</lang>
 
=={{header|J}}==
Line 262 ⟶ 337:
Nevertheless, this is doable, though it necessarily departs from the definition specified at [[Doubly-linked_list/Definition#J]].
 
<langsyntaxhighlight lang="j">coclass'DoublyLinkedListElement'
create=:3 :0
this=:coname''
'predecessor successor data'=:y
successor__predecessor=: predecessor__successor=: this
)</langsyntaxhighlight>
 
Here, when we create a new list element, we need to specify its successor node and its predecessor node and the data to be stored in the node. To start a new list we will need a node that can be the head and the tail of the list -- this will be the successor node for the last element of the list and the predecessor node for the first element of the list:
 
<langsyntaxhighlight lang="j">coclass'DoublyLinkedListHead'
create=:3 :0
predecessor=:successor=:this=: coname''
)</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java">public class Node<T> {
private T element;
private Node<T> next, prev;
Line 319 ⟶ 394:
return prev;
}
}</langsyntaxhighlight>
 
For use with [[Java]] 1.4 and below, delete all "<T>"s and replace T's with "Object".
Line 325 ⟶ 400:
=={{header|JavaScript}}==
Inherits from LinkedList (see [[Singly-Linked_List_(element)#JavaScript]])
<langsyntaxhighlight lang="javascript">function DoublyLinkedList(value, next, prev) {
this._value = value;
this._next = next;
Line 351 ⟶ 426:
}
 
var head = createDoublyLinkedListFromArray([10,20,30,40]);</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<syntaxhighlight lang="julia">abstract type AbstractNode{T} end
 
struct EmptyNode{T} <: AbstractNode{T} end
mutable struct Node{T} <: AbstractNode{T}
value::T
pred::AbstractNode{T}
succ::AbstractNode{T}
end</syntaxhighlight>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.1.2
 
class Node<T: Number>(var data: T, var prev: Node<T>? = null, var next: Node<T>? = null) {
override fun toString(): String {
val sb = StringBuilder(this.data.toString())
var node = this.next
while (node != null) {
sb.append(" -> ", node.data.toString())
node = node.next
}
return sb.toString()
}
}
 
fun main(args: Array<String>) {
val n1 = Node(1)
val n2 = Node(2, n1)
n1.next = n2
val n3 = Node(3, n2)
n2.next = n3
println(n1)
println(n2)
println(n3)
}</syntaxhighlight>
 
{{out}}
<pre>
1 -> 2 -> 3
2 -> 3
3
</pre>
 
=={{header|Lang}}==
<syntaxhighlight lang="lang">
&Node = {
$next
$prev
$data
}
</syntaxhighlight>
 
=={{header|Lua}}==
see [[Doubly-linked_list/Definition#Lua]], essentially:
<syntaxhighlight lang="lua">local node = { data=data, prev=nil, next=nil }</syntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Mathematica and the Wolfram Language have no lower-level way of handling pointers. It does have a built-in, compilable doubly-linked list data structure:
<syntaxhighlight lang="mathematica">CreateDataStructure["DoublyLinkedList"]</syntaxhighlight>
 
=={{header|Modula-2}}==
 
<langsyntaxhighlight lang="modula2">TYPE
Link = POINTER TO LinkRcd;
LinkRcd = RECORD
Prev, Next: Link;
Data: INTEGER
END;</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">type
Node[T] = ref TNode[T]
 
TNode[T] = object
next, prev: Node[T]
data: T</langsyntaxhighlight>
 
=={{header|Oberon-2}}==
<syntaxhighlight lang="oberon2">
MODULE Box;
TYPE
Object* = POINTER TO ObjectDesc;
ObjectDesc* = (* ABSTRACT *) RECORD
END;
 
(* ... *)
END Box.
 
MODULE Collections;
TYPE
Node* = POINTER TO NodeDesc;
NodeDesc* = (* ABSTRACT *) RECORD
prev-,next-: Node;
value-: Box.Object;
END;
 
(* ... *)
END Collections.
</syntaxhighlight>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">class ListNode {
@value : Base;
@next : ListNode;
Line 403 ⟶ 563:
return @previous;
}
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
===Imperative===
<langsyntaxhighlight lang="ocaml">type 'a dlink = {
mutable data: 'a;
mutable next: 'a dlink option;
Line 448 ⟶ 608:
in
aux
;;</langsyntaxhighlight>
 
<langsyntaxhighlight lang="ocaml"># let dl = dlink_of_list [1;2;3;4;5] in
iter_forward_dlink (Printf.printf "%d\n") dl ;;
1
Line 457 ⟶ 617:
4
5
- : unit = ()</langsyntaxhighlight>
 
===Functional===
Line 464 ⟶ 624:
examples of this page and its task, but in regular OCaml these kind of imperative structures can be advantageously replaced by a functional equivalent, that can be use in the same area, which is to have a list of elements and be able to point to one of these. We can use this type:
 
<langsyntaxhighlight lang="ocaml">type 'a nav_list = 'a list * 'a * 'a list</langsyntaxhighlight>
 
The middle element is the pointed item, and the two lists are the
previous and the following items.
Here are the associated functions:
<langsyntaxhighlight lang="ocaml">let nav_list_of_list = function
| hd::tl -> [], hd, tl
| [] -> invalid_arg "empty list"
Line 486 ⟶ 646:
prev_tl, prev, item::next
| _ ->
failwith "begin of nav_list reached"</langsyntaxhighlight>
<langsyntaxhighlight lang="ocaml"># let nl = nav_list_of_list [1;2;3;4;5] ;;
val nl : 'a list * int * int list = ([], 1, [2; 3; 4; 5])
# let nl = next nl ;;
Line 495 ⟶ 655:
 
# current nl ;;
- : int = 3</langsyntaxhighlight>
 
=={{header|Oforth}}==
Line 501 ⟶ 661:
Complete definition is here : [[../Definition#Oforth]]
 
<langsyntaxhighlight lang="oforth">Object Class new: DNode(value, mutable prev, mutable next)</langsyntaxhighlight>
 
=={{header|Oz}}==
We show how to create a new node as a record value.
<langsyntaxhighlight lang="oz">fun {CreateNewNode Value}
node(prev:{NewCell _}
next:{NewCell _}
value:Value)
end</langsyntaxhighlight>
Note: this is for illustrative purposes only. In a real Oz program, you would use one of the existing data types.
 
=={{header|Pascal}}==
 
<langsyntaxhighlight lang="pascal">type link_ptr = ^link;
data_ptr = ^data; (* presumes that type 'data' is defined above *)
link = record
Line 520 ⟶ 680:
next: link_ptr;
data: data_ptr;
end;</langsyntaxhighlight>
 
=={{header|Perl}}==
 
<langsyntaxhighlight lang="perl">my %node = (
data => 'say what',
next => \%foo_node,
prev => \%bar_node,
);
$node{next} = \%quux_node; # mutable</langsyntaxhighlight>
=={{header|Perl 6}}==
 
=={{header|Phix}}==
<lang perl6>role DLElem[::T] {
In Phix, types are used for validation and debugging rather than specification purposes. For extensive run-time checking you could use
has DLElem[T] $.prev is rw;
<!--<syntaxhighlight lang="phix">-->
has DLElem[T] $.next is rw;
<span style="color: #008080;">enum</span> <span style="color: #000000;">NEXT</span><span style="color: #0000FF;">,</span><span style="color: #000000;">PREV</span><span style="color: #0000FF;">,</span><span style="color: #000000;">DATA</span>
has T $.payload = T;
<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>
<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: #0000FF;"><</span><span style="color: #000000;">i</span><span style="color: #0000FF;">></span><span style="color: #000000;">udt</span><span style="color: #0000FF;"></</span><span style="color: #000000;">i</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> <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;">PREV</span><span style="color: #0000FF;">]))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">type</span>
<!--</syntaxhighlight>-->
But more often you would just use the builtin sequences. See also [[Singly-linked_list/Element_definition#Phix|Singly-linked_list/Element_definition]].
 
Memory is automatically reclaimed the moment items are no longer needed.
method pre-insert(T $payload) {
die "Can't insert before beginning" unless $!prev;
my $elem = ::?CLASS.new(:$payload);
$!prev.next = $elem;
$elem.prev = $!prev;
$elem.next = self;
$!prev = $elem;
$elem;
}
 
Note that automatic typechecking does not occur under pwa/p2js, that is desktop/Phix only (for the debugging stage) but you can invoke a type such as the above explicitly.
method post-insert(T $payload) {
die "Can't insert after end" unless $!next;
my $elem = ::?CLASS.new(:$payload);
$!next.prev = $elem;
$elem.next = $!next;
$elem.prev = self;
$!next = $elem;
$elem;
}
 
method delete {
die "Can't delete a sentinel" unless $!prev and $!next;
$!next.prev = $!prev;
$!prev.next = $!next; # conveniently returns next element
}
}</lang>
 
=={{header|PL/I}}==
<lang PL/I>
define structure
1 Node,
2 value fixed decimal,
2 back_pointer handle(Node),
2 fwd_pointer handle(Node);
 
P = NEW(: Node :); /* Creates a node, and lets P point at it. */
get (P => value); /* Reads in a value to the node we just created. */
 
/* Assuming that back_pointer and fwd_pointer point at other nodes, */
/* we can say ... */
P = P => fwd_pointer; /* P now points at the next node. */
...
P = P => back_pointer; /* P now points at the previous node. */
</lang>
 
=={{header|PicoLisp}}==
Line 595 ⟶ 718:
With that, 'cddr' can be used to access the next, and 'cadr' to access the
previous element.
<syntaxhighlight lang="picolisp">(de 2tail (X DLst)
<lang PicoLisp># 'cons' an element to a doubly-linked list
(delet 2consL (Xcdr DLst)
(con DLst (cons X L NIL))
(if L
(con (cdr L) (cdr DLst))
(set DLst (cdr DLst)) ) ) )
 
(de 2head (X DLst)
(let L (car DLst) # Get current data list
(set DLst (cons X NIL L)) # Prepend two new cons pairs
Line 604 ⟶ 733:
 
# We prepend 'not' to the list in the previous example
(2cons2head 'not *DLst)</langsyntaxhighlight>
For output of the example data, see [[Doubly-linked list/Traversal#PicoLisp]].
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
define structure
1 Node,
2 value fixed decimal,
2 back_pointer handle(Node),
2 fwd_pointer handle(Node);
 
P = NEW(: Node :); /* Creates a node, and lets P point at it. */
get (P => value); /* Reads in a value to the node we just created. */
 
/* Assuming that back_pointer and fwd_pointer point at other nodes, */
/* we can say ... */
P = P => fwd_pointer; /* P now points at the next node. */
...
P = P => back_pointer; /* P now points at the previous node. */
</syntaxhighlight>
 
=={{header|Plain English}}==
When you define a <code>thing</code>, you are defining a record as a doubly-linked list element. <code>next</code> and <code>previous</code> fields are implicitly added to the record that can be used to build and traverse a list.
<syntaxhighlight lang="plainenglish">An element is a thing with a number.</syntaxhighlight>
 
=={{header|Pop11}}==
 
<langsyntaxhighlight lang="pop11">uses objectclass;
define :class Link;
slot next = [];
slot prev = [];
slot data = [];
enddefine;</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Structure node
*prev.node
*next.node
value.i
EndStructure</langsyntaxhighlight>
 
=={{header|Python}}==
 
<langsyntaxhighlight lang="python">class Node(object):
def __init__(self, data = None, prev = None, next = None):
self.prev = prev
Line 642 ⟶ 794:
while c != None:
yield c
c = c.prev</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">
(define-struct dlist (head tail) #:mutable)
(define-struct dlink (content prev next) #:mutable)
</syntaxhighlight>
</lang>
 
See the functions on the [[Doubly-Linked List]] page for the usage of these structures.
 
=={{header|Raku}}==
(formerly Perl 6)
 
<syntaxhighlight lang="raku" line>role DLElem[::T] {
has DLElem[T] $.prev is rw;
has DLElem[T] $.next is rw;
has T $.payload = T;
 
method pre-insert(T $payload) {
die "Can't insert before beginning" unless $!prev;
my $elem = ::?CLASS.new(:$payload);
$!prev.next = $elem;
$elem.prev = $!prev;
$elem.next = self;
$!prev = $elem;
$elem;
}
 
method post-insert(T $payload) {
die "Can't insert after end" unless $!next;
my $elem = ::?CLASS.new(:$payload);
$!next.prev = $elem;
$elem.next = $!next;
$elem.prev = self;
$!next = $elem;
$elem;
}
 
method delete {
die "Can't delete a sentinel" unless $!prev and $!next;
$!next.prev = $!prev;
$!prev.next = $!next; # conveniently returns next element
}
}</syntaxhighlight>
 
=={{header|REXX}}==
Line 678 ⟶ 865:
║ @del k,m ─── deletes the M items starting with item K. ║
╚═════════════════════════════════════════════════════════════════════════╝
<langsyntaxhighlight lang="rexx">/*REXX program implements various List Manager functions (see the documentation above).*/
call sy 'initializing the list.' ; call @init
call sy 'building list: Was it a cat I saw' ; call @put "Was it a cat I saw"
Line 721 ⟶ 908:
/*──────────────────────────────────────────────────────────────────────────────────────*/
@show: procedure expose $.; parse arg k,m,dir; if dir==-1 & k=='' then k=$.#
m=p(m $.#); call @parms 'kmd'; say @get(k,m, dir); return</langsyntaxhighlight>
'''output'''
<pre>
Line 761 ⟶ 948:
=={{header|Ruby}}==
Extending [[Singly-Linked List (element)#Ruby]]
<langsyntaxhighlight lang="ruby">class DListNode < ListNode
attr_accessor :prev
# accessors :succ and :value are inherited
Line 780 ⟶ 967:
end
 
list = DListNode.from_values 1,2,3,4</langsyntaxhighlight>
 
=={{header|Rust}}==
Line 786 ⟶ 973:
 
=== Simply using the standard library ===
<langsyntaxhighlight lang="rust">use std::collections::LinkedList;
fn main() {
// Doubly linked list containing 32-bit integers
let list = LinkedList::<i32>::new();
}</langsyntaxhighlight>
 
=== The behind-the-scenes implementation ===
Doubly linked lists present a problem in Rust due to its ownership model. There cannot be two mutable references to the same object, so what are we to do? Below are the relevant lines (with added comments) from the <code>std</code> implementation ([https://doc.rust-lang.org/std/collections/struct.LinkedList.html Documentation] [https://github.com/rust-lang/rust/blob/master/src/libcollections/linked_list.rs Source]).
 
The standard library uses the (currently) unstable `Shared<T>` type which indicates that the ownership of its contained type has shared ownership. It is guaranteed not to be null, is variant over <code>T</code> (meaning that an <code>&Shared<&'static T></code> may be used where a <code>&Shared<&'a T></code> is expected, indicates to the compiler that it may own a <code>T</code>) and may be dereferenced to a mutable pointer (<code>*mut T</code>). All of the above may be accomplished in standard stable Rust, except for the non-null guarantee which allows the compiler to make a few extra optimizations.
In order to circumvent the multiple mutable references, raw C-like pointers are used. Note that these cannot be dereferenced with guaranteed safety and thus dereferencing is relegated to <code>unsafe {}</code> blocks.
 
<syntaxhighlight lang ="rust">pub struct LinkedList<T> { // User-facing implementation
head: Option<Shared<Node<T>>>,
length: usize,
list_headtail: LinkOption<Shared<Node<T>>>,
list_taillen: Rawlink<Node<T>>usize,
marker: PhantomData<Box<Node<T>>>, // Indicates that we logically own a boxed (owned pointer) Node<T>>
}
 
type Link<T> = Option<Box<Node<T>>>; // Type definition
 
struct Rawlink<T> { // Pointer is wrapped in struct so that Option-like methods can be added to it later (wrappers around NULL checks)
p: *mut T, // Raw mutable pointer
}
 
struct Node<T> {
next: LinkOption<Shared<Node<T>>>,
prev: RawlinkOption<Shared<Node<T>>>,
valueelement: T,
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var node = Hash.new(
data => 'say what',
next => foo_node,
Line 822 ⟶ 1,004:
);
 
node{:next} = quux_node; # mutable</langsyntaxhighlight>
 
=={{header|Swift}}==
 
<syntaxhighlight lang="swift">typealias NodePtr<T> = UnsafeMutablePointer<Node<T>>
 
class Node<T> {
var value: T
fileprivate var prev: NodePtr<T>?
fileprivate var next: NodePtr<T>?
 
init(value: T, prev: NodePtr<T>? = nil, next: NodePtr<T>? = nil) {
self.value = value
self.prev = prev
self.next = next
}
}
</syntaxhighlight>
 
=={{header|Tcl}}==
{{eff note|Tcl|list}}
{{works with|Tcl|8.6}} or {{libheader|TclOO}}
<langsyntaxhighlight lang="tcl">oo::class create List {
variable content next prev
constructor {value {list ""}} {
Line 846 ⟶ 1,045:
set prev {*}$args
}
}</langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
 
<langsyntaxhighlight lang="vbnet">Public Class Node(Of T)
Public Value As T
Public [Next] As Node(Of T)
Public Previous As Node(Of T)
End Class</langsyntaxhighlight>
 
=={{header|Wren}}==
{{libheader|Wren-llist}}
The DNode class in the above module is the element type for the DLinkedList class which is a generic doubly-linked list. The latter is implemented in such a way that the user does not need to deal directly with DNode 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 DNode
 
var dn1 = DNode.new(1)
var dn2 = DNode.new(2)
dn1.next = dn2
dn1.prev = null
dn2.prev = dn1
dn2.next = null
System.print(["node 1", "data = %(dn1.data)", "prev = %(dn1.prev)", "next = %(dn1.next)"])
System.print(["node 2", "data = %(dn2.data)", "prev = %(dn2.prev)", "next = %(dn2.next)"])</syntaxhighlight>
 
{{out}}
<pre>
[node 1, data = 1, prev = null, next = 2]
[node 2, data = 2, prev = 1, next = null]
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang "XPL0">
def \Node\ Prev, Data, Next; \Element (Node) definition
</syntaxhighlight>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">class Node{
fcn init(_value){ var value,_prev=_valueVoid,next,prev; } _next=Void)
{ var value=_value, prev=_prev, next=_next; }
fcn toString{ value.toString() }
}</syntaxhighlight>
}
<syntaxhighlight lang="zkl">a,b:=Node(1),Node("twothree");
a.next=b; b.prev=a;
println(a.next," ",b.prev);</langsyntaxhighlight>
{{out}}
<pre>
twothree 1
</pre>
 
9,476

edits