Doubly-linked list/Traversal: Difference between revisions

m
m (Regularize header markup to recommended on category page)
m (→‎{{header|Wren}}: Minor tidy)
 
(4 intermediate revisions by 4 users not shown)
Line 11:
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}}
<langsyntaxhighlight Actionlang="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!
Line 101:
 
Clear()
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Doubly-linked_list_traversal.png Screenshot from Atari 8-bit computer]
Line 118:
=={{header|Ada}}==
{{works with|Ada 2005}}
<langsyntaxhighlight Adalang="ada">with Ada.Containers.Doubly_Linked_Lists;
with Ada.Text_IO;
 
Line 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 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 292:
PURGE list;
forward traversal(list)
)</langsyntaxhighlight>
{{out}}
<pre>
Line 311:
=={{header|ALGOL W}}==
Using the element type and insertion routine from the Doubly Linked List/Eleemnt Insertion task.
<langsyntaxhighlight lang="algolw">begin
% record type to hold an element of a doubly linked list of integers %
record DListIElement ( reference(DListIElement) prev
Line 359:
end while_e_ne_null
end
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 374:
</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 659 ⟶ 694:
.include "../affichage.inc"
 
</syntaxhighlight>
</lang>
 
=={{header|AutoHotkey}}==
Line 665 ⟶ 700:
 
=={{header|Axe}}==
<langsyntaxhighlight lang="axe">LINK(L₁,1)→A
LINK(L₁+10,2)→B
LINK(L₁+50,3)→C
Line 684 ⟶ 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 725 ⟶ 760:
here.pNext% = new{}
ENDPROC
</syntaxhighlight>
</lang>
Output:
<pre>Traverse forwards:
Line 737 ⟶ 772:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">// A doubly linked list of strings;
#include <stdio.h>
#include <stdlib.h>
Line 864 ⟶ 899:
//uhhh-- delete list??
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
 
Line 893 ⟶ 928:
}
}
}</langsyntaxhighlight>
Output:
<pre>
Line 910 ⟶ 945:
=={{header|C++}}==
{{works with|C++11}}
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <list>
 
Line 919 ⟶ 954:
std::cout << i << ' ';
std::cout << '\n';
}</langsyntaxhighlight>
{{out}}
<pre>
Line 927 ⟶ 962:
=={{header|Clojure}}==
Given the definition in [[../Definition#Clojure]],
<langsyntaxhighlight Clojurelang="clojure">(def dl (double-list [:a :b :c :d]))
;=> #'user/dl
 
Line 944 ⟶ 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 955 ⟶ 990:
dll[].writeln;
dll[].retro.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>ABCD
Line 962 ⟶ 997:
===User-defined Doubly-linked list===
Same output.
<langsyntaxhighlight lang="d">struct Node(T) {
T data;
typeof(this)* prev, next;
Line 991 ⟶ 1,026:
p.data.write;
writeln;
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
<langsyntaxhighlight lang="delphi">uses system ;
 
type
Line 1,019 ⟶ 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 1,042 ⟶ 1,077:
}
}
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="e">? def list := makeDLList()
# value: <>
 
Line 1,057 ⟶ 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 SharpF_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
open System.Collections.Generic
 
Line 1,089 ⟶ 1,124:
printfn ""
traverseBackward cs
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,101 ⟶ 1,136:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">Dim As Integer i, MiLista()
 
For i = 0 To Int(Rnd * 100)+25
Line 1,118 ⟶ 1,153:
Print MiLista(i)
Next i
Sleep</langsyntaxhighlight>
 
 
Line 1,125 ⟶ 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 1,186 ⟶ 1,221:
}
fmt.Println("")
}</langsyntaxhighlight>
Output:
<pre>
Line 1,196 ⟶ 1,231:
 
=={{header|Groovy}}==
<langsyntaxhighlight Groovylang="groovy">class DoubleLinkedListTraversing {
static void main(args) {
def linkedList = (1..9).collect() as LinkedList
Line 1,210 ⟶ 1,245:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,217 ⟶ 1,252:
 
=={{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,235 ⟶ 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,286 ⟶ 1,321:
every (node := l2.traverse_backwards ()) do
write (node.value)
end</langsyntaxhighlight>
 
Output:
Line 1,301 ⟶ 1,336:
 
=={{header|J}}==
<langsyntaxhighlight lang="j">traverse=:1 :0
work=. result=. conew 'DoublyLinkedListHead'
current=. y
Line 1,308 ⟶ 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,315 ⟶ 1,350:
{{works with|Java|8 or higher}}
 
<langsyntaxhighlight lang="java">
package com.rosettacode;
 
Line 1,335 ⟶ 1,370:
doubleLinkedList.descendingIterator().forEachRemaining(System.out::print);
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,343 ⟶ 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,359 ⟶ 1,394:
var head = createDoublyLinkedListFromArray([10,20,30,40]);
head.print();
head.getTail().printBackward();</langsyntaxhighlight>
 
outputs:
Line 1,373 ⟶ 1,408:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">mutable struct DLNode{T}
value::T
pred::Union{DLNode{T}, Nothing}
Line 1,420 ⟶ 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,427 ⟶ 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,506 ⟶ 1,541:
println("First to last : ${ll.firstToLast()}")
println("Last to first : ${ll.lastToFirst()}")
}</langsyntaxhighlight>
 
{{out}}
Line 1,516 ⟶ 1,551:
=={{header|Lua}}==
Begin with this: [[Doubly-linked_list/Definition#Lua]], then extend with this:
<langsyntaxhighlight lang="lua">--------------
-- TRAVERSAL:
--------------
Line 1,538 ⟶ 1,573:
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()</langsyntaxhighlight>
{{out}}
<pre>Forward: 1,2,3,4,5,
Line 1,544 ⟶ 1,579:
 
=={{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,691 ⟶ 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,773 ⟶ 1,808:
 
for i in l.traverseBackward():
echo "< ", i</langsyntaxhighlight>
 
=={{header|Oberon-2}}==
<langsyntaxhighlight lang="oberon2">
MODULE Collections;
IMPORT Box;
Line 1,807 ⟶ 1,842:
 
END Collections.
</syntaxhighlight>
</lang>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
class Traverse {
function : Main(args : String[]) ~ Nil {
Line 1,835 ⟶ 1,870:
}
}
</syntaxhighlight>
</lang>
 
<pre>
Line 1,858 ⟶ 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,877 ⟶ 1,912:
 
"\nTraversal (end to beginning) : " println
dl revEach: n [ n . ] ;</langsyntaxhighlight>
 
{{out}}
Line 1,890 ⟶ 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,943 ⟶ 1,978:
{InsertAfter A C}
{Walk A Show}
{WalkBackwards A Show}</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 1,949 ⟶ 1,984:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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;">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>
Line 1,979 ⟶ 2,014:
<span style="color: #0000FF;">?</span><span style="color: #008000;">"=="</span>
<span style="color: #000000;">show</span><span style="color: #0000FF;">(</span><span style="color: #000000;">PREV</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,993 ⟶ 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 2,003 ⟶ 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 2,021 ⟶ 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 2,077 ⟶ 2,112:
t = t => back_pointer;
end;
end doubly_linked_list;</langsyntaxhighlight>
Output:
<pre>
Line 2,104 ⟶ 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 2,122 ⟶ 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 2,154 ⟶ 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 2,171 ⟶ 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 2,181 ⟶ 2,216:
(if dlink
(loop (cons (dlink-content dlink) elements) (dlink-next dlink))
elements)))</langsyntaxhighlight>
 
=={{header|Raku}}==
Line 2,187 ⟶ 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 2,194 ⟶ 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,272 ⟶ 2,307:
$.@=_
call @adjust
return</langsyntaxhighlight>
'''output'''
<pre style="height:30ex;overflow:scroll">
Line 2,311 ⟶ 2,346:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Doubly-linked list/Traversal
 
Line 2,323 ⟶ 2,358:
see travback
see nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,338 ⟶ 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,352 ⟶ 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,397 ⟶ 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,441 ⟶ 2,476:
follow.data!
step
follow := follow.previous;;</langsyntaxhighlight>
 
Both of these produce the following output:
Line 2,464 ⟶ 2,499:
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">import java.util
 
object DoublyLinkedListTraversal extends App {
Line 2,475 ⟶ 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,502 ⟶ 2,537:
$first foreach char { puts $char }
puts "Backward..."
$last revforeach char { puts $char }</langsyntaxhighlight>
Which produces this output:
<pre>Forward...
Line 2,518 ⟶ 2,553:
{{libheader|Wren-llist}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "./llist" for DLinkedList
import "./fmt" for Fmt
 
// create a new doubly-linked list and add the first 50 positive integers to it
Line 2,534 ⟶ 2,569:
Fmt.write("$4d ", i)
if (i % 10 == 1) System.print()
}</langsyntaxhighlight>
 
{{out}}
Line 2,549 ⟶ 2,584:
20 19 18 17 16 15 14 13 12 11
10 9 8 7 6 5 4 3 2 1
</langpre>
 
=={{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,562 ⟶ 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