Doubly-linked list/Traversal: Difference between revisions

m
(→‎{{header|Raku}}: Fix up some internal links)
m (→‎{{header|Wren}}: Minor tidy)
 
(13 intermediate revisions by 10 users not shown)
Line 7:
{{Template:See also lists}}
<br><br>
 
=={{header|Action!}}==
The user must type in the monitor the following command after compilation and before running the program!<pre>SET EndProg=*</pre>
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang="action!">CARD EndProg ;required for ALLOCATE.ACT
 
INCLUDE "D2:ALLOCATE.ACT" ;from the Action! Tool Kit. You must type 'SET EndProg=*' from the monitor after compiling, but before running this program!
 
DEFINE PTR="CARD"
DEFINE NODE_SIZE="6"
TYPE ListNode=[INT data PTR prv,nxt]
 
ListNode POINTER listBegin,listEnd
 
PROC Append(INT v)
ListNode POINTER n
 
n=Alloc(NODE_SIZE)
n.data=v
n.prv=listEnd
n.nxt=0
IF listEnd THEN
listEnd.nxt=n
ELSE
listBegin=n
FI
listEnd=n
RETURN
 
PROC Clear()
ListNode POINTER n,next
 
n=listBegin
WHILE n
DO
next=n.nxt
Free(n,NODE_SIZE)
n=next
OD
listBegin=0
listEnd=0
RETURN
 
PROC ForwardTraverse()
ListNode POINTER n
 
n=listBegin
PrintE("Forward traverse:")
Print("(")
WHILE n
DO
PrintI(n.data)
IF n.nxt THEN
Print(", ")
FI
n=n.nxt
OD
PrintE(")")
RETURN
 
PROC BackwardTraverse()
ListNode POINTER n
 
n=listEnd
PrintE("Backward traverse")
Print("(")
WHILE n
DO
PrintI(n.data)
IF n.prv THEN
Print(", ")
FI
n=n.prv
OD
PrintE(")")
RETURN
 
PROC Main()
INT i
Put(125) PutE() ;clear screen
AllocInit(0)
listBegin=0
listEnd=0
 
FOR i=0 TO 50
DO
Append(i*i)
OD
ForwardTraverse()
PutE()
BackwardTraverse()
 
Clear()
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Doubly-linked_list_traversal.png Screenshot from Atari 8-bit computer]
<pre>
Forward traverse:
(0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361,
400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296,
1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401, 2500)
 
Backward traverse
(2500, 2401, 2304, 2209, 2116, 2025, 1936, 1849, 1764, 1681, 1600, 1521, 1444, 1369, 1296,
1225, 1156, 1089, 1024, 961, 900, 841, 784, 729, 676, 625, 576, 529, 484, 441, 400, 361,
324, 289, 256, 225, 196, 169, 144, 121, 100, 81, 64, 49, 36, 25, 16, 9, 4, 1, 0)
</pre>
 
=={{header|Ada}}==
{{works with|Ada 2005}}
<langsyntaxhighlight Adalang="ada">with Ada.Containers.Doubly_Linked_Lists;
with Ada.Text_IO;
 
Line 36 ⟶ 144:
My_List.Reverse_Iterate (Print'Access);
Ada.Text_IO.New_Line;
end Traversing;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
LinkedList.alg:<langsyntaxhighlight lang="algol68"># Node struct - contains next and prev NODE pointers and DATA #
MODE NODE = STRUCT(
DATA data,
Line 140 ⟶ 248:
travel := prev OF travel
OD
)</langsyntaxhighlight>
 
main.alg:<langsyntaxhighlight lang="algol68">PR READ "LinkedList.alg" PR;
 
MODE EMPLOYEE = STRUCT(STRING name, INT salary, INT years);
Line 184 ⟶ 292:
PURGE list;
forward traversal(list)
)</langsyntaxhighlight>
{{out}}
<pre>
Line 201 ⟶ 309:
</pre>
 
=={{header|ALGOL W}}==
Using the element type and insertion routine from the Doubly Linked List/Eleemnt Insertion task.
<syntaxhighlight lang="algolw">begin
% 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 %
% inserts a new element into the list, before e %
reference(DListIElement) procedure insertIntoDListIBefore( reference(DListIElement) value e
; integer value v
);
begin
reference(DListIElement) newElement;
newElement := DListIElement( null, v, e );
if e not = null then begin
% the element we are inserting before is not null %
reference(DListIElement) ePrev;
ePrev := prev(e);
prev(newElement) := ePrev;
prev(e) := newElement;
if ePrev not = null then next(ePrev) := newElement
end if_e_ne_null ;
newElement
end insertIntoDListiAfter ;
 
begin
reference(DListIElement) head, e, last;
head := null;
head := insertIntoDListIBefore( head, 1701 );
head := insertIntoDListIBefore( head, 9000 );
e := insertIntoDListIBefore( next(head), 90210 );
e := insertIntoDListIBefore( next(e), 4077 );
e := head;
last := null;
write( "Forward:" );
while e not = null do begin
write( i_w := 1, s_w := 0, " ", iValue(e) );
last := e;
e := next(e)
end while_e_ne_null ;
write( "Backward:" );
e := last;
while e not = null do begin
write( i_w := 1, s_w := 0, " ", iValue(e) );
last := e;
e := prev(e)
end while_e_ne_null
end
end.</syntaxhighlight>
{{out}}
<pre>
Forward:
9000
90210
4077
1701
Backward:
1701
4077
90210
9000
</pre>
 
=={{header|Applesoft BASIC}}==
<syntaxhighlight lang="gwbasic"> 100 REM BUILD THE LIST
110 FOR I = 20 TO 40 STEP 10
120 LET S$ = STR$ (I): GOSUB 260"APPEND"
130 NEXT I
140 REM TRAVERSE FORWARDS
150 LET N = HEAD
160 FOR Q = 1 TO 1
170 IF N < > NIL THEN PRINT S$(N)" ";:N = N(N):Q = 0
180 NEXT Q
190 PRINT
200 REM TRAVERSE BACKWARDS
210 LET N = TAIL
220 FOR Q = 1 TO 1
230 IF N < > NIL THEN PRINT S$(N)" ";:N = P(N):Q = 0
240 NEXT Q
250 END
260 REM APPEND S$
270 LET NIL = - 1
280 LET P(L) = NIL
290 LET N(L) = NIL
300 REM TRAVERSE UNTIL LAST NODE FOUND
310 FOR Q = 1 TO 1
320 IF N(N) < > NIL THEN N = N(N):Q = 0
330 NEXT Q
340 REM NEW NODE
350 LET S$(L) = S$
360 LET N(L) = NIL
370 IF N < > L THEN P(L) = N
380 REM POINT THE LAST NODE AT THE NEW NODE
390 IF N < > L THEN N(N) = L
400 LET TAIL = L
410 LET N = TAIL
420 LET L = L + 1
430 RETURN</syntaxhighlight>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program transDblList.s */
Line 486 ⟶ 694:
.include "../affichage.inc"
 
</syntaxhighlight>
</lang>
 
=={{header|AutoHotkey}}==
Line 492 ⟶ 700:
 
=={{header|Axe}}==
<langsyntaxhighlight lang="axe">LINK(L₁,1)→A
LINK(L₁+10,2)→B
LINK(L₁+50,3)→C
Line 511 ⟶ 719:
Disp VALUE(I)▶Dec,i
PREV(I)→I
End</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> DIM node{pPrev%, pNext%, iData%}
DIM a{} = node{}, b{} = node{}, c{} = node{}
Line 552 ⟶ 760:
here.pNext% = new{}
ENDPROC
</syntaxhighlight>
</lang>
Output:
<pre>Traverse forwards:
Line 564 ⟶ 772:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">// A doubly linked list of strings;
#include <stdio.h>
#include <stdlib.h>
Line 691 ⟶ 899:
//uhhh-- delete list??
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
 
Line 720 ⟶ 928:
}
}
}</langsyntaxhighlight>
Output:
<pre>
Line 737 ⟶ 945:
=={{header|C++}}==
{{works with|C++11}}
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <list>
 
Line 746 ⟶ 954:
std::cout << i << ' ';
std::cout << '\n';
}</langsyntaxhighlight>
{{out}}
<pre>
Line 754 ⟶ 962:
=={{header|Clojure}}==
Given the definition in [[../Definition#Clojure]],
<langsyntaxhighlight Clojurelang="clojure">(def dl (double-list [:a :b :c :d]))
;=> #'user/dl
 
Line 771 ⟶ 979:
;=> #:double_list.Node{:prev #<Object...>, :next #<Object...>, :data :c, :key #<Object...>}
;=> #:double_list.Node{:prev #<Object...>, :next #<Object...>, :data :b, :key #<Object...>}
;=> #:double_list.Node{:prev nil, :next #<Object...>, :data :a, :key #<Object...>})</langsyntaxhighlight>
 
=={{header|D}}==
===Standard Doubly-linked List===
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.container, std.range;
 
Line 782 ⟶ 990:
dll[].writeln;
dll[].retro.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>ABCD
Line 789 ⟶ 997:
===User-defined Doubly-linked list===
Same output.
<langsyntaxhighlight lang="d">struct Node(T) {
T data;
typeof(this)* prev, next;
Line 818 ⟶ 1,026:
p.data.write;
writeln;
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
<langsyntaxhighlight lang="delphi">uses system ;
 
type
Line 846 ⟶ 1,054:
while not (pList^.prev = NIL) do pList := pList^.prev ;
 
end;</langsyntaxhighlight>
 
=={{header|E}}==
{{incorrect|E|Doesn't work, probably due to a bug in the list definition: runs over the beginning of the list. Needs debugging.}}
Given the definition in [[../Definition#E]],
<langsyntaxhighlight lang="e">def traverse(list) {
var node := list.atFirst()
while (true) {
Line 869 ⟶ 1,077:
}
}
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="e">? def list := makeDLList()
# value: <>
 
Line 884 ⟶ 1,092:
3
2
1</langsyntaxhighlight>
 
=={{header|Erlang}}==
The task in [[Doubly-linked_list/Element_insertion]] uses traversal as proof that the insertion worked.
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
open System.Collections.Generic
 
Line 916 ⟶ 1,124:
printfn ""
traverseBackward cs
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 925 ⟶ 1,133:
=={{header|Fortran}}==
see [[Doubly-linked list/Definition#Fortran]]
 
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">Dim As Integer i, MiLista()
 
For i = 0 To Int(Rnd * 100)+25
Redim Preserve MiLista(i)
MiLista(i) = Rnd * 314
Next
 
'Tour from the beginning
For i = Lbound(MiLista) To Ubound(MiLista)
Print MiLista(i)
Next i
 
Print
'Travel from the end
For i = Ubound(MiLista) To Lbound(MiLista) Step -1
Print MiLista(i)
Next i
Sleep</syntaxhighlight>
 
 
=={{header|Go}}==
Line 930 ⟶ 1,160:
 
Also note that there is a doubly linked list in the Go standard library in package container/list.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 991 ⟶ 1,221:
}
fmt.Println("")
}</langsyntaxhighlight>
Output:
<pre>
Line 999 ⟶ 1,229:
From tail: B C A
</pre>
 
=={{header|Groovy}}==
<syntaxhighlight lang="groovy">class DoubleLinkedListTraversing {
static void main(args) {
def linkedList = (1..9).collect() as LinkedList
 
linkedList.each {
print it
}
 
println()
 
linkedList.reverseEach {
print it
}
}
}</syntaxhighlight>
 
{{out}}
<pre>123456789
987654321</pre>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">main = print . traverse True $ create [10,20,30,40]
 
data DList a = Leaf | Node { prev::(DList a), elt::a, next::(DList a) }
Line 1,019 ⟶ 1,270:
traverse _ Leaf = []
traverse True (Node l v Leaf) = v : v : traverse False l
traverse dir (Node l v r) = v : traverse dir (if dir then r else l)</langsyntaxhighlight>
 
==Icon and {{header|Unicon}}==
Uses Unicon classes.
<langsyntaxhighlight Uniconlang="unicon">class DoubleLink (value, prev_link, next_link)
 
# insert given node after this one, removing its existing connections
Line 1,070 ⟶ 1,321:
every (node := l2.traverse_backwards ()) do
write (node.value)
end</langsyntaxhighlight>
 
Output:
Line 1,085 ⟶ 1,336:
 
=={{header|J}}==
<langsyntaxhighlight lang="j">traverse=:1 :0
work=. result=. conew 'DoublyLinkedListHead'
current=. y
Line 1,092 ⟶ 1,343:
end.
result
)</langsyntaxhighlight>
 
This traverses a doubly linked list, applying the verb u to the data in each list element and creates a new doubly linked list containing the results. A reference to the new doubly linked list is returned.
Line 1,099 ⟶ 1,350:
{{works with|Java|8 or higher}}
 
<langsyntaxhighlight lang="java">
package com.rosettacode;
 
Line 1,119 ⟶ 1,370:
doubleLinkedList.descendingIterator().forEachRemaining(System.out::print);
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,127 ⟶ 1,378:
=={{header|JavaScript}}==
See [[Doubly-Linked List (element)#JavaScript]]. The <code>traverse()</code> and <code>print()</code> functions have been inherited from [[Singly-Linked List (traversal)#JavaScript]].
<langsyntaxhighlight lang="javascript">DoublyLinkedList.prototype.getTail = function() {
var tail;
this.traverse(function(node){tail = node;});
Line 1,143 ⟶ 1,394:
var head = createDoublyLinkedListFromArray([10,20,30,40]);
head.print();
head.getTail().printBackward();</langsyntaxhighlight>
 
outputs:
Line 1,157 ⟶ 1,408:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">mutable struct DLNode{T}
value::T
pred::Union{DLNode{T}, Nothing}
Line 1,204 ⟶ 1,455:
print("From beginning to end: "); printconnected(node1)
print("From end to beginning: "); printconnected(node1, fromtail = true)
</langsyntaxhighlight> {{output}} <pre>
From beginning to end: 1 -> 2 -> 3
From end to beginning: 3 -> 2 -> 1
Line 1,211 ⟶ 1,462:
=={{header|Kotlin}}==
To complete this task, we just need to add a couple of traversal functions to the class we defined in the [[Doubly-linked list/Definition]] task:
<langsyntaxhighlight lang="scala">// version 1.1.2
 
class LinkedList<E> {
Line 1,290 ⟶ 1,541:
println("First to last : ${ll.firstToLast()}")
println("Last to first : ${ll.lastToFirst()}")
}</langsyntaxhighlight>
 
{{out}}
Line 1,297 ⟶ 1,548:
Last to first : 4 -> 3 -> 2 -> 1
</pre>
 
=={{header|Lua}}==
Begin with this: [[Doubly-linked_list/Definition#Lua]], then extend with this:
<syntaxhighlight lang="lua">--------------
-- TRAVERSAL:
--------------
List.iterateForward = function(self)
local function iter(self, node)
if node then return node.next else return self.head end
end
return iter, self, nil
end
List.iterateReverse = function(self)
local function iter(self, node)
if node then return node.prev else return self.tail end
end
return iter, self, nil
end
 
---------
-- TEST:
---------
local list = List()
for i = 1, 5 do list:insertTail(i) end
io.write("Forward: ") for node in list:iterateForward() do io.write(node.data..",") end print()
io.write("Reverse: ") for node in list:iterateReverse() do io.write(node.data..",") end print()</syntaxhighlight>
{{out}}
<pre>Forward: 1,2,3,4,5,
Reverse: 5,4,3,2,1,</pre>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
struct block,nxt as ulong,prev as ulong,nm as char[20],age as long'Our structure of the blocks in our list.
 
Line 1,446 ⟶ 1,726:
calldll #kernel32,"HeapDestroy",hHeap as ulong,ret as void
end sub
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">type
List[T] = object
head, tail: Node[T]
Line 1,528 ⟶ 1,808:
 
for i in l.traverseBackward():
echo "< ", i</langsyntaxhighlight>
 
=={{header|Oberon-2}}==
<langsyntaxhighlight lang="oberon2">
MODULE Collections;
IMPORT Box;
Line 1,562 ⟶ 1,842:
 
END Collections.
</syntaxhighlight>
</lang>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
class Traverse {
function : Main(args : String[]) ~ Nil {
Line 1,590 ⟶ 1,870:
}
}
</syntaxhighlight>
</lang>
 
<pre>
Line 1,613 ⟶ 1,893:
Defining #forEachNext and #forEachPrev allow to traverse this double linked list using #forEach: and #revEach: syntax
 
<langsyntaxhighlight lang="oforth">DList method: forEachNext
dup ifNull: [ drop @head ifNull: [ false ] else: [ @head @head true] return ]
next dup ifNull: [ drop false ] else: [ dup true ] ;
Line 1,632 ⟶ 1,912:
 
"\nTraversal (end to beginning) : " println
dl revEach: n [ n . ] ;</langsyntaxhighlight>
 
{{out}}
Line 1,645 ⟶ 1,925:
=={{header|Oz}}==
Warning: Highly unidiomatic code. (Use built-in lists instead.)
<langsyntaxhighlight lang="oz">declare
proc {Walk Node Action}
case Node of nil then skip
Line 1,698 ⟶ 1,978:
{InsertAfter A C}
{Walk A Show}
{WalkBackwards A Show}</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 1,704 ⟶ 1,984:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>enum NEXT,PREV,DATA
<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>
constant empty_dll = {{1,1}}
<span style="color: #008080;">constant</span> <span style="color: #000000;">empty_dll</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">}}</span>
sequence dll = empty_dll
<span style="color: #004080;">sequence</span> <span style="color: #000000;">dll</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">deep_copy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">empty_dll</span><span style="color: #0000FF;">)</span>
 
procedure insert_after(object data, integer pos=1)
<span style="color: #008080;">procedure</span> <span style="color: #000000;">insert_after</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">data</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">pos</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
integer prv = dll[pos][PREV]
<span style="color: #004080;">integer</span> <span style="color: #000000;">prv</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">dll</span><span style="color: #0000FF;">[</span><span style="color: #000000;">pos</span><span style="color: #0000FF;">][</span><span style="color: #000000;">PREV</span><span style="color: #0000FF;">]</span>
dll = append(dll,{pos,prv,data})
<span style="color: #000000;">dll</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dll</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">pos</span><span style="color: #0000FF;">,</span><span style="color: #000000;">prv</span><span style="color: #0000FF;">,</span><span style="color: #000000;">data</span><span style="color: #0000FF;">})</span>
if prv!=0 then
<span style="color: #008080;">if</span> <span style="color: #000000;">prv</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
dll[prv][NEXT] = length(dll)
<span style="color: #000000;">dll</span><span style="color: #0000FF;">[</span><span style="color: #000000;">prv</span><span style="color: #0000FF;">][</span><span style="color: #000000;">NEXT</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dll</span><span style="color: #0000FF;">)</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
dll[pos][PREV] = length(dll)
<span style="color: #000000;">dll</span><span style="color: #0000FF;">[</span><span style="color: #000000;">pos</span><span style="color: #0000FF;">][</span><span style="color: #000000;">PREV</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dll</span><span style="color: #0000FF;">)</span>
end procedure
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
 
insert_after("ONE")
<span style="color: #000000;">insert_after</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"ONE"</span><span style="color: #0000FF;">)</span>
insert_after("TWO")
<span style="color: #000000;">insert_after</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"TWO"</span><span style="color: #0000FF;">)</span>
insert_after("THREE")
<span style="color: #000000;">insert_after</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"THREE"</span><span style="color: #0000FF;">)</span>
 
?dll
<span style="color: #0000FF;">?</span><span style="color: #000000;">dll</span>
 
procedure show(integer d)
<span style="color: #008080;">procedure</span> <span style="color: #000000;">show</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">)</span>
integer idx = dll[1][d]
<span style="color: #004080;">integer</span> <span style="color: #000000;">idx</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">dll</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">][</span><span style="color: #000000;">d</span><span style="color: #0000FF;">]</span>
while idx!=1 do
<span style="color: #008080;">while</span> <span style="color: #000000;">idx</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
?dll[idx][DATA]
<span style="color: #0000FF;">?</span><span style="color: #000000;">dll</span><span style="color: #0000FF;">[</span><span style="color: #000000;">idx</span><span style="color: #0000FF;">][</span><span style="color: #000000;">DATA</span><span style="color: #0000FF;">]</span>
idx = dll[idx][d]
<span style="color: #000000;">idx</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">dll</span><span style="color: #0000FF;">[</span><span style="color: #000000;">idx</span><span style="color: #0000FF;">][</span><span style="color: #000000;">d</span><span style="color: #0000FF;">]</span>
end while
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
end procedure
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
show(NEXT)
<span style="color: #000000;">show</span><span style="color: #0000FF;">(</span><span style="color: #000000;">NEXT</span><span style="color: #0000FF;">)</span>
?"=="
<span style="color: #0000FF;">?</span><span style="color: #008000;">"=="</span>
show(PREV)</lang>
<span style="color: #000000;">show</span><span style="color: #0000FF;">(</span><span style="color: #000000;">PREV</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,746 ⟶ 2,028:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp"># Print the elements a doubly-linked list
(de 2print (DLst)
(for (L (car DLst) L (cddr L))
Line 1,756 ⟶ 2,038:
(for (L (cdr DLst) L (cadr L))
(printsp (car L)) )
(prinl) )</langsyntaxhighlight>
Output for the example data produced in
[[Doubly-linked list/Definition#PicoLisp]] and
Line 1,774 ⟶ 2,056:
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">/* To implement a doubly-linked list -- i.e., a 2-way linked list. */
doubly_linked_list: proc options (main);
 
Line 1,830 ⟶ 2,112:
t = t => back_pointer;
end;
end doubly_linked_list;</langsyntaxhighlight>
Output:
<pre>
Line 1,857 ⟶ 2,139:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">NewList MyData.i() ; Create a double linked list holding a single value (integer)
 
;Set up a randomly long linked list in the range 25-125 elements
Line 1,875 ⟶ 2,157:
Repeat
Debug MyData() ; Present the value in the current cell
Until Not PreviousElement(MyData())</langsyntaxhighlight>
 
=={{header|Python}}==
This provides two solutions. One that explicitly builds a linked list and traverses it two ways, and another which uses pythons combined list/array class. Unless two lists explicitly needed to be spliced together in O(1) time, or a double linked list was needed for some other reason, most python programmers would probably use the second solution.
<langsyntaxhighlight lang="python">class List:
def __init__(self, data, next=None, prev=None):
self.data = data
Line 1,907 ⟶ 2,189:
while node != None:
print(node.data)
node = node.prev</langsyntaxhighlight>
 
This produces the desired output. However, I expect most python programmers would do the following instead:
 
<langsyntaxhighlight lang="python">l = [ 10, 20, 30, 40 ]
for i in l:
print(i)
for i in reversed(l): # reversed produces an iterator, so only O(1) memory is used
print(i)</langsyntaxhighlight>
 
Double-ended queues in python are provided by the collections.deque class and the array/list type can perform all the operations of a C++ vector (and more), so building one's own doubly-linked list would be restricted to very specialized situations.
Line 1,924 ⟶ 2,206:
These functions traverse the list in the two directions.
They create a native (singly-linked) list by adding to the front, so they traverse in the reverse order from the desired result order.
<langsyntaxhighlight lang="racket">(define (dlist-elements dlist)
(let loop ([elements '()] [dlink (dlist-tail dlist)])
(if dlink
Line 1,934 ⟶ 2,216:
(if dlink
(loop (cons (dlink-content dlink) elements) (dlink-next dlink))
elements)))</langsyntaxhighlight>
 
=={{header|Raku}}==
Line 1,940 ⟶ 2,222:
 
Since the list routines are supplied by the generic roles defined in [[Doubly-linked_list/Definition#Raku]], it suffices to say:
<syntaxhighlight lang="raku" perl6line>say $dll.list;
say $dll.reverse;</langsyntaxhighlight>
These automatically return just the payloads, hiding the elements containing the forward and backward pointers.
 
Line 1,947 ⟶ 2,229:
REXX doesn't have linked lists, as there are no pointers (or handles).
However, linked lists can be simulated with lists in REXX.
<langsyntaxhighlight lang="rexx">/*REXX program that implements various List Manager functions. */
/*┌────────────────────────────────────────────────────────────────────┐
┌─┘ Functions of the List Manager └─┐
Line 2,025 ⟶ 2,307:
$.@=_
call @adjust
return</langsyntaxhighlight>
'''output'''
<pre style="height:30ex;overflow:scroll">
Line 2,064 ⟶ 2,346:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Doubly-linked list/Traversal
 
Line 2,076 ⟶ 2,358:
see travback
see nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,091 ⟶ 2,373:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">class DListNode
def get_tail
# parent class (ListNode) includes Enumerable, so the find method is available to us
Line 2,105 ⟶ 2,387:
head = DListNode.from_array([:a, :b, :c])
head.each {|node| p node.value}
head.get_tail.each_previous {|node| p node.value}</langsyntaxhighlight>
 
=={{header|Salmon}}==
Without explicit type information:
<langsyntaxhighlight Salmonlang="salmon">class item(init_data)
{
variable next,
Line 2,150 ⟶ 2,432:
follow.data!
step
follow := follow.previous;;</langsyntaxhighlight>
 
With explicit type information:
<langsyntaxhighlight Salmonlang="salmon">class item(init_data : string)
{
variable next: item | {null},
Line 2,194 ⟶ 2,476:
follow.data!
step
follow := follow.previous;;</langsyntaxhighlight>
 
Both of these produce the following output:
Line 2,217 ⟶ 2,499:
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">import java.util
 
object DoublyLinkedListTraversal extends App {
Line 2,228 ⟶ 2,510:
traverse(ll.iterator)
traverse(ll.descendingIterator)
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
Assuming that the <code>List</code> class from [[Doubly-Linked List (element)#Tcl|this other task]] is already present...
<langsyntaxhighlight lang="tcl"># Modify the List class to add the iterator methods
oo::define List {
method foreach {varName script} {
Line 2,255 ⟶ 2,537:
$first foreach char { puts $char }
puts "Backward..."
$last revforeach char { puts $char }</langsyntaxhighlight>
Which produces this output:
<pre>Forward...
Line 2,267 ⟶ 2,549:
b
a</pre>
 
=={{header|Wren}}==
{{libheader|Wren-llist}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./llist" for DLinkedList
import "./fmt" for Fmt
 
// create a new doubly-linked list and add the first 50 positive integers to it
var dll = DLinkedList.new(1..50)
 
// traverse the doubly-linked list from head to tail
for (i in dll) {
Fmt.write("$4d ", i)
if (i % 10 == 0) System.print()
}
System.print()
// traverse the doubly-linked list from tail to head
for (i in dll.reversed) {
Fmt.write("$4d ", i)
if (i % 10 == 1) System.print()
}</syntaxhighlight>
 
{{out}}
<pre>
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
 
50 49 48 47 46 45 44 43 42 41
40 39 38 37 36 35 34 33 32 31
30 29 28 27 26 25 24 23 22 21
20 19 18 17 16 15 14 13 12 11
10 9 8 7 6 5 4 3 2 1
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang "XPL0">def \Node\ Prev, Data, Next; \Element (Node) definition
def SizeofInt = 4;
 
proc Insert(NewNode, Node); \Insert NewNode after Node
int NewNode, Node, NextNode;
[NextNode:= Node(Next);
NextNode(Prev):= NewNode;
NewNode(Next):= NextNode;
NewNode(Prev):= Node;
Node(Next):= NewNode;
];
 
int Head(3), Tail(3); \Doubly linked list definition
int N, NewNode, Node;
[\Further define (initialize) the doubly linked list
Head(Next):= Tail;
Tail(Prev):= Head;
\Insert some Nodes containing square data
for N:= 1 to 10 do
[NewNode:= Reserve(3*SizeofInt);
NewNode(Data):= N*N;
Insert(NewNode, Head);
];
\Traverse list from Head to Tail
Node:= Head(Next);
while Node # Tail do
[IntOut(0, Node(Data)); ChOut(0, ^ );
Node:= Node(Next);
];
CrLf(0);
\Traverse list from Tail to Head
Node:= Tail(Prev);
while Node # Head do
[IntOut(0, Node(Data)); ChOut(0, ^ );
Node:= Node(Prev);
];
CrLf(0);
]</syntaxhighlight>
{{out}}
<pre>
100 81 64 49 36 25 16 9 4 1
1 4 9 16 25 36 49 64 81 100
</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">class Node{
fcn init(_value,_prev=Void,_next=Void)
{ var value=_value, prev=_prev, next=_next; }
Line 2,279 ⟶ 2,642:
b
}
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">a,c := Node("a"), a.append("b").append("c");
n:=a; while(n){ print(n," "); n=n.next }
println();
n:=c; while(n){ print(n," "); n=n.prev }
println();</langsyntaxhighlight>
{{out}}
<pre>
9,476

edits