Doubly-linked list/Element definition: Difference between revisions
Doubly-linked list/Element definition (view source)
Revision as of 11:59, 28 November 2023
, 5 months ago→{{header|Wren}}: Minor tidy
m (→{{header|Phix}}: replaced "notonline" tag with a comment.) |
m (→{{header|Wren}}: Minor tidy) |
||
(8 intermediate revisions by 6 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}}==
<
type Link_Access is access Link;
type Link is record
Line 19 ⟶ 28:
Prev : Link_Access := null;
Data : Integer;
end record;</
Using generics, the specification might look like this:
<
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;</
In Ada 2005 this example can be written without declaration of an access type:
<
Next : not null access Link := Link'Unchecked_Access;
Prev : not null access Link := Link'Unchecked_Access;
Data : Integer;
end record;</
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.
Line 58 ⟶ 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'''<
CO REQUIRES:
MODE OBJVALUE = ~ # Mode/type of actual obj to be queued #
Line 72 ⟶ 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 #</
=={{header|ALGOL W}}==
<
record DListIElement ( reference(DListIElement) prev
; integer iValue
; reference(DListIElement) next
);
% additional record types would be required for other element types %</
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
Line 97 ⟶ 106:
.struct NDlist_value + 4
NDlist_fin:
</syntaxhighlight>
=={{header|AutoHotkey}}==
Line 103 ⟶ 112:
=={{header|Axe}}==
<
r₂→{r₁}ʳ
0→{r₁+2}ʳ
Line 120 ⟶ 129:
Lbl VALUE
{r₁}ʳ
Return</
=={{header|
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<
</syntaxhighlight>
=={{header|Bracmat}}==
<
=={{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.
<
{
struct Node *next;
struct Node *prev;
void *data;
};</
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.
<syntaxhighlight lang="c">
struct Node;
typedef struct Node* Node;
Line 148 ⟶ 158:
void* data;
};
</syntaxhighlight>
=={{header|C sharp|C#}}==
<
{
public int Item { get; set; }
Line 163 ⟶ 173:
Next = next;
}
}</
=={{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:
<
struct Node
{
Line 173 ⟶ 183:
Node* prev;
T data;
};</
=={{header|Clojure}}==
Line 179 ⟶ 189:
This sort of mutable structure is not idiomatic in Clojure. [[../Definition#Clojure]] or a finger tree implementation would be better.
<
(defn new-node [prev next data]
(Node. (ref prev) (ref next) data))</
=={{header|Common Lisp}}==
<
(defstruct dlink content prev next)</
See the functions on the [[Doubly-Linked List]] page for the usage of these structures.
Line 193 ⟶ 203:
=={{header|D}}==
A default constructor is implicit:
<
T data;
typeof(this)* prev, next;
Line 201 ⟶ 211:
alias N = Node!int;
N* n = new N(10);
}</
=={{header|Delphi}}==
<
type
Line 216 ⟶ 226:
end;
}</
=={{header|E}}==
Line 222 ⟶ 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).
<
def element {
to setValue(v) { value := v }
Line 235 ⟶ 245:
return element
}</
=={{header|Erlang}}==
Using the code in [[Doubly-linked_list/Definition]] the element is defined by:
<syntaxhighlight lang="erlang">
new( Data ) -> erlang:spawn( fun() -> loop( Data, noprevious, nonext ) end ).
</syntaxhighlight>
=={{header|F_Sharp|F#}}==
<
type 'a DLElm = {
mutable prev: 'a DLElm option
Line 250 ⟶ 260:
mutable next: 'a DLElm option
}
</syntaxhighlight>
=={{header|Factor}}==
<
=={{header|Fortran}}==
In ISO Fortran 95 or later:
<
real :: data
type(node), pointer :: next => null(), previous => null()
Line 264 ⟶ 274:
! . . . .
!
type( node ), target :: head</
=={{header|FreeBASIC}}==
<
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</
=={{header|Go}}==
<
string
next, prev *dlNode
}</
Or, using the [http://golang.org/pkg/container/list/#Element container/list] package:
<
var node list.Element
// and using: node.Next(), node.Prev(), node.Value</
=={{header|Haskell}}==
Line 290 ⟶ 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.
<
data DList a = Leaf | Node (DList a) a (DList a)
Line 304 ⟶ 314:
where current = Node l v next
next = updateRight nr new
</syntaxhighlight>
==Icon and {{header|Unicon}}==
Line 310 ⟶ 320:
Uses Unicon classes.
<syntaxhighlight lang="unicon">
class DoubleLink (value, prev_link, next_link)
initially (value, prev_link, next_link)
Line 317 ⟶ 327:
self.next_link := next_link
end
</syntaxhighlight>
=={{header|J}}==
Line 327 ⟶ 337:
Nevertheless, this is doable, though it necessarily departs from the definition specified at [[Doubly-linked_list/Definition#J]].
<
create=:3 :0
this=:coname''
'predecessor successor data'=:y
successor__predecessor=: predecessor__successor=: this
)</
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:
<
create=:3 :0
predecessor=:successor=:this=: coname''
)</
=={{header|Java}}==
{{works with|Java|1.5+}}
<
private T element;
private Node<T> next, prev;
Line 384 ⟶ 394:
return prev;
}
}</
For use with [[Java]] 1.4 and below, delete all "<T>"s and replace T's with "Object".
Line 390 ⟶ 400:
=={{header|JavaScript}}==
Inherits from LinkedList (see [[Singly-Linked_List_(element)#JavaScript]])
<
this._value = value;
this._next = next;
Line 416 ⟶ 426:
}
var head = createDoublyLinkedListFromArray([10,20,30,40]);</
=={{header|Julia}}==
{{works with|Julia|0.6}}
<
struct EmptyNode{T} <: AbstractNode{T} end
Line 428 ⟶ 438:
pred::AbstractNode{T}
succ::AbstractNode{T}
end</
=={{header|Kotlin}}==
<
class Node<T: Number>(var data: T, var prev: Node<T>? = null, var next: Node<T>? = null) {
Line 454 ⟶ 464:
println(n2)
println(n3)
}</
{{out}}
Line 462 ⟶ 472:
3
</pre>
=={{header|Lang}}==
<syntaxhighlight lang="lang">
&Node = {
$next
$prev
$data
}
</syntaxhighlight>
=={{header|Lua}}==
see [[Doubly-linked_list/Definition#Lua]], essentially:
<
=={{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:
<
=={{header|Modula-2}}==
<
Link = POINTER TO LinkRcd;
LinkRcd = RECORD
Prev, Next: Link;
Data: INTEGER
END;</
=={{header|Nim}}==
<
Node[T] = ref TNode[T]
TNode[T] = object
next, prev: Node[T]
data: T</
=={{header|Oberon-2}}==
<
MODULE Box;
TYPE
Line 509 ⟶ 528:
(* ... *)
END Collections.
</syntaxhighlight>
=={{header|Objeck}}==
<
@value : Base;
@next : ListNode;
Line 544 ⟶ 563:
return @previous;
}
}</
=={{header|OCaml}}==
===Imperative===
<
mutable data: 'a;
mutable next: 'a dlink option;
Line 589 ⟶ 608:
in
aux
;;</
<
iter_forward_dlink (Printf.printf "%d\n") dl ;;
1
Line 598 ⟶ 617:
4
5
- : unit = ()</
===Functional===
Line 605 ⟶ 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:
<
The middle element is the pointed item, and the two lists are the
previous and the following items.
Here are the associated functions:
<
| hd::tl -> [], hd, tl
| [] -> invalid_arg "empty list"
Line 627 ⟶ 646:
prev_tl, prev, item::next
| _ ->
failwith "begin of nav_list reached"</
<
val nl : 'a list * int * int list = ([], 1, [2; 3; 4; 5])
# let nl = next nl ;;
Line 636 ⟶ 655:
# current nl ;;
- : int = 3</
=={{header|Oforth}}==
Line 642 ⟶ 661:
Complete definition is here : [[../Definition#Oforth]]
<
=={{header|Oz}}==
We show how to create a new node as a record value.
<
node(prev:{NewCell _}
next:{NewCell _}
value:Value)
end</
Note: this is for illustrative purposes only. In a real Oz program, you would use one of the existing data types.
=={{header|Pascal}}==
<
data_ptr = ^data; (* presumes that type 'data' is defined above *)
link = record
Line 661 ⟶ 680:
next: link_ptr;
data: data_ptr;
end;</
=={{header|Perl}}==
<
data => 'say what',
next => \%foo_node,
prev => \%bar_node,
);
$node{next} = \%quux_node; # mutable</
=={{header|Phix}}==
In Phix, types are used for validation and debugging rather than specification purposes. For extensive run-time checking you could use
<!--<
<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>
<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>
<!--</
But more often you would just use the builtin sequences. See also [[Singly-linked_list/Element_definition#Phix|Singly-linked_list/Element_definition]].
Line 699 ⟶ 718:
With that, 'cddr' can be used to access the next, and 'cadr' to access the
previous element.
<
(let L (cdr DLst)
(con DLst (cons X L NIL))
Line 714 ⟶ 733:
# We prepend 'not' to the list in the previous example
(2head 'not *DLst)</
For output of the example data, see [[Doubly-linked list/Traversal#PicoLisp]].
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
define structure
1 Node,
Line 733 ⟶ 752:
...
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.
<
=={{header|Pop11}}==
<
define :class Link;
slot next = [];
slot prev = [];
slot data = [];
enddefine;</
=={{header|PureBasic}}==
<
*prev.node
*next.node
value.i
EndStructure</
=={{header|Python}}==
<
def __init__(self, data = None, prev = None, next = None):
self.prev = prev
Line 775 ⟶ 794:
while c != None:
yield c
c = c.prev</
=={{header|Racket}}==
<
(define-struct dlist (head tail) #:mutable)
(define-struct dlink (content prev next) #:mutable)
</syntaxhighlight>
See the functions on the [[Doubly-Linked List]] page for the usage of these structures.
Line 789 ⟶ 808:
(formerly Perl 6)
<syntaxhighlight lang="raku"
has DLElem[T] $.prev is rw;
has DLElem[T] $.next is rw;
Line 819 ⟶ 838:
$!prev.next = $!next; # conveniently returns next element
}
}</
=={{header|REXX}}==
Line 846 ⟶ 865:
║ @del k,m ─── deletes the M items starting with item K. ║
╚═════════════════════════════════════════════════════════════════════════╝
<
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 889 ⟶ 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</
'''output'''
<pre>
Line 929 ⟶ 948:
=={{header|Ruby}}==
Extending [[Singly-Linked List (element)#Ruby]]
<
attr_accessor :prev
# accessors :succ and :value are inherited
Line 948 ⟶ 967:
end
list = DListNode.from_values 1,2,3,4</
=={{header|Rust}}==
Line 954 ⟶ 973:
=== Simply using the standard library ===
<
fn main() {
// Doubly linked list containing 32-bit integers
let list = LinkedList::<i32>::new();
}</
=== The behind-the-scenes implementation ===
Line 965 ⟶ 984:
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.
<
head: Option<Shared<Node<T>>>,
tail: Option<Shared<Node<T>>>,
Line 976 ⟶ 995:
prev: Option<Shared<Node<T>>>,
element: T,
}</
=={{header|Sidef}}==
<
data => 'say what',
next => foo_node,
Line 985 ⟶ 1,004:
);
node{:next} = quux_node; # mutable</
=={{header|Swift}}==
<
class Node<T> {
Line 1,002 ⟶ 1,021:
}
}
</syntaxhighlight>
=={{header|Tcl}}==
{{eff note|Tcl|list}}
{{works with|Tcl|8.6}} or {{libheader|TclOO}}
<
variable content next prev
constructor {value {list ""}} {
Line 1,026 ⟶ 1,045:
set prev {*}$args
}
}</
=={{header|Visual Basic .NET}}==
<
Public Value As T
Public [Next] As Node(Of T)
Public Previous As Node(Of T)
End Class</
=={{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.
<
var dn1 = DNode.new(1)
Line 1,048 ⟶ 1,067:
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)"])</
{{out}}
Line 1,055 ⟶ 1,074:
[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}}==
<
fcn init(_value,_prev=Void,_next=Void)
{ var value=_value, prev=_prev, next=_next; }
fcn toString{ value.toString() }
}</
<
a.next=b; b.prev=a;
println(a.next," ",b.prev);</
{{out}}
<pre>
|