Singly-linked list/Traversal: Difference between revisions

From Rosetta Code
Content added Content deleted
No edit summary
m (minor (mostly whitespace) fixes)
Line 9: Line 9:
{
{
doStuff(i);
doStuff(i);
}</lang>
}

</lang>
=={{header|Ada}}==
=={{header|Ada}}==
The Ada standard container library provides a doubly-linked list. List traversal is demonstrated for the forward links.
The Ada standard container library provides a doubly-linked list. List traversal is demonstrated for the forward links.
Line 35: Line 35:
=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
{{works with|ALGOL 68|Revision 1 - no extensions to language used}}
{{works with|ALGOL 68|Revision 1 - no extensions to language used}}

{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}

{{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]}}
{{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]}}

Linked lists are not built into ALGOL 68 ''per se'', nor any available standard library. However Linked lists are presented in standard text
Linked lists are not built into ALGOL 68 ''per se'', nor any available standard library. However Linked lists are presented in standard text
book examples. Or can be manually constructed, eg:
book examples. Or can be manually constructed, eg:
Line 105: Line 102:


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==

<lang lisp>(dolist (x list)
<lang lisp>(dolist (x list)
(print x))</lang>
(print x))</lang>
Line 116: Line 112:


=={{header|D}}==
=={{header|D}}==

Traversal using list defined in [[Singly-Linked_List_(element)#D | Singly-Linked list element - D]].
Traversal using list defined in [[Singly-Linked_List_(element)#D | Singly-Linked list element - D]].
<lang D>// a is a beginning of a list);
<lang D>// a is a beginning of a list);
Line 138: Line 133:
}</lang>
}</lang>


=={{header|Delphi}}==

<lang delphi>uses system ;
=={{header|Delphi / Pascal}}==

<lang>
uses system ;
type
type
Line 163: Line 155:
while not (pList^.Next = NIL) do pList := pList^.Next ;
while not (pList^.Next = NIL) do pList := pList^.Next ;
end;
end;</lang>
</lang>





=={{header|E}}==
=={{header|E}}==

Using a list made from tuples:
Using a list made from tuples:

<lang e>var linkedList := [1, [2, [3, [4, [5, [6, [7, null]]]]]]]
<lang e>var linkedList := [1, [2, [3, [4, [5, [6, [7, null]]]]]]]


Line 181: Line 167:


Using a list made from the structure defined at [[Singly-Linked List (element)#E|Singly-Linked List (element)]]:
Using a list made from the structure defined at [[Singly-Linked List (element)#E|Singly-Linked List (element)]]:

<lang e>var linkedList := makeLink(1, makeLink(2, makeLink(3, empty)))
<lang e>var linkedList := makeLink(1, makeLink(2, makeLink(3, empty)))


Line 190: Line 175:


=={{header|Ela}}==
=={{header|Ela}}==

<lang ela>let traverse [] = []
<lang ela>let traverse [] = []
traverse (x::xs) = x :: traverse xs</lang>
traverse (x::xs) = x :: traverse xs</lang>
Line 220: Line 204:


=={{header|Fantom}}==
=={{header|Fantom}}==

Using the definitions from [[Singly-Linked_List_(element_insertion)]]:
Using the definitions from [[Singly-Linked_List_(element_insertion)]]:
<lang fantom> // traverse the linked list

<lang fantom>
// traverse the linked list
Node? current := a
Node? current := a
while (current != null)
while (current != null)
Line 230: Line 211:
echo (current.value)
echo (current.value)
current = current.successor
current = current.successor
}
}</lang>
</lang>


=={{header|Forth}}==
=={{header|Forth}}==
Line 253: Line 233:
for iter := start; iter != nil; iter = iter.Next {
for iter := start; iter != nil; iter = iter.Next {
fmt.Println(iter)
fmt.Println(iter)
}</lang>
}
</lang>


=={{header|Haskell}}==
=={{header|Haskell}}==
Line 271: Line 250:


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==

Using either the record or class-based definitions from [[Singly-Linked List (element)#Icon_and_Unicon|Singly-Linked List (element) in Icon and Unicon]]:
Using either the record or class-based definitions from [[Singly-Linked List (element)#Icon_and_Unicon|Singly-Linked List (element) in Icon and Unicon]]:
<lang Icon>procedure main ()

<lang Icon>
procedure main ()
ns := Node(1, Node(2, Node (3)))
ns := Node(1, Node(2, Node (3)))
until /ns do { # repeat until ns is null
until /ns do { # repeat until ns is null
Line 281: Line 257:
ns := ns.successor
ns := ns.successor
}
}
end
end</lang>
</lang>

Prints the numbers 1, 2, 3 in turn.
Prints the numbers 1, 2, 3 in turn.


=={{header|J}}==
=={{header|J}}==

Using the implementation mentioned at [[Singly-Linked List (element)#J|Singly-Linked List (element) in J]], we can apply a function <tt>foo</tt> to each node the following way:
Using the implementation mentioned at [[Singly-Linked List (element)#J|Singly-Linked List (element) in J]], we can apply a function <tt>foo</tt> to each node the following way:

<lang J>foo"0 {:"1 list</lang>
<lang J>foo"0 {:"1 list</lang>


=={{header|Java}}==
=={{header|Java}}==
{{works with|Java|1.5+}}
{{works with|Java|1.5+}}

For Java.util.LinkedList<T>, use a for each loop (from [[Loop Structures]]):
For Java.util.LinkedList<T>, use a for each loop (from [[Loop Structures]]):
<lang java>LinkedList<Type> list = new LinkedList<Type>();
<lang java>LinkedList<Type> list = new LinkedList<Type>();
Line 302: Line 273:
System.out.println(i);
System.out.println(i);
}</lang>
}</lang>
Note that <code>java.util.LinkedList</code> can also perform as a stack, queue, or doubly-linked list.

Note that Java.util.LinkedList can also perform as a stack, queue, or doubly-linked list.


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 329: Line 299:


=={{header|Objective-C}}==
=={{header|Objective-C}}==

(See [[Singly-Linked List (element)]])
(See [[Singly-Linked List (element)]])

<lang objc>RCListElement *current;
<lang objc>RCListElement *current;
for(current=first_of_the_list; current != nil; current = [current next] )
for(current=first_of_the_list; current != nil; current = [current next] )
Line 338: Line 306:
// id dat_obj = [current datum];
// id dat_obj = [current datum];
}</lang>
}</lang>



=={{header|OCaml}}==
=={{header|OCaml}}==

<lang ocaml># let li = ["big"; "fjords"; "vex"; "quick"; "waltz"; "nymph"] in
<lang ocaml># let li = ["big"; "fjords"; "vex"; "quick"; "waltz"; "nymph"] in
List.iter print_endline li ;;
List.iter print_endline li ;;
Line 351: Line 317:
nymph
nymph
- : unit = ()</lang>
- : unit = ()</lang>

=={{header|Perl 6}}==
=={{header|Perl 6}}==
Built-in list processing in Perl is not specifically based on singly-linked lists, but works at a higher abstraction level that encapsulates such implementation choices. Nonetheless, it's trivial to use the <tt>Pair</tt> type to build what is essentially a Lisp-style cons list, and in fact, the <tt>=></tt> pair constructor is right associative for precisely that reason.
Built-in list processing in Perl is not specifically based on singly-linked lists, but works at a higher abstraction level that encapsulates such implementation choices. Nonetheless, it's trivial to use the <tt>Pair</tt> type to build what is essentially a Lisp-style cons list, and in fact, the <tt>=></tt> pair constructor is right associative for precisely that reason.
We traverse such a list here using a 3-part loop:
We traverse such a list here using a 3-part loop:

<lang perl6>my $list = 1 => 2 => 3 => 4 => 5 => 6 => Mu;
<lang perl6>my $list = 1 => 2 => 3 => 4 => 5 => 6 => Mu;


Line 396: Line 362:
(X Y Z)
(X Y Z)
999</pre>
999</pre>

=={{header|Protium}}==
=={{header|Protium}}==
This makes a list of the Chinese Public Holiday and lists them first till last and then last till first.
This makes a list of the Chinese Public Holiday and lists them first till last and then last till first.

<lang html><@ LETCNSLSTLIT>public holidays|開國紀念日^和平紀念日^婦女節、兒童節合併假期^清明節^國慶日^春節^端午節^中秋節^農曆除夕</@>
<lang html><@ LETCNSLSTLIT>public holidays|開國紀念日^和平紀念日^婦女節、兒童節合併假期^清明節^國慶日^春節^端午節^中秋節^農曆除夕</@>
<@ OMT>From First to Last</@>
<@ OMT>From First to Last</@>
Line 407: Line 373:
<@ ITEFORSZELSTLIT>public holidays|
<@ ITEFORSZELSTLIT>public holidays|
<@ SAYLST>...</@><@ ACTMOVBKWLST>...</@>
<@ SAYLST>...</@><@ ACTMOVBKWLST>...</@>
</@>
</@></lang>
</lang>

This variable length Simplified Chinese rendition of the same code is
This variable length Simplified Chinese rendition of the same code is

<lang html><# 指定构造列表字串>public holidays|開國紀念日^和平紀念日^婦女節、兒童節合併假期^清明節^國慶日^春節^端午節^中秋節^農曆除夕</#>
<lang html><# 指定构造列表字串>public holidays|開國紀念日^和平紀念日^婦女節、兒童節合併假期^清明節^國慶日^春節^端午節^中秋節^農曆除夕</#>
<# 忽略>From First to Last</#>
<# 忽略>From First to Last</#>
Line 436: Line 399:
<lang python>for node in lst:
<lang python>for node in lst:
print node.value</lang>
print node.value</lang>

Any Python class can define ''next()'' and ''__iter__()'' methods so that it can be used with the normal ''for'' iteration syntax. In this example the "lst" could be an instance of any Python list, tuple, dictionary, or any sort of object which defines an iterator. It could also be a generator (a type of function which ''yields'' results upon each successive invocation). The notion of a "singly linked list" is somewhat more primitive than normal Python built-in objects.
Any Python class can define ''next()'' and ''__iter__()'' methods so that it can be used with the normal ''for'' iteration syntax. In this example the "lst" could be an instance of any Python list, tuple, dictionary, or any sort of object which defines an iterator. It could also be a generator (a type of function which ''yields'' results upon each successive invocation). The notion of a "singly linked list" is somewhat more primitive than normal Python built-in objects.
<lang python>class LinkedList(object):
<lang python>class LinkedList(object):
Line 467: Line 429:


=={{header|Retro}}==
=={{header|Retro}}==

<lang Retro>: traverse ( l- ) repeat @ 0; again ;</lang>
<lang Retro>: traverse ( l- ) repeat @ 0; again ;</lang>

Or, using combinators:
Or, using combinators:

<lang Retro>last [ drop ] ^types'LIST each@</lang>
<lang Retro>last [ drop ] ^types'LIST each@</lang>

With combinators you can also perform an operation on each element in a linked list:
With combinators you can also perform an operation on each element in a linked list:

<lang Retro>last [ @d->name puts space ] ^types'LIST each@</lang>
<lang Retro>last [ @d->name puts space ] ^types'LIST each@</lang>


Line 497: Line 454:


=={{header|Scala}}==
=={{header|Scala}}==

Scala has a '''Seq''' (for ''sequence'') trait that is more general than singly-linked lists. These two examples are equivalent for SLL, but the second would be faster for other sequence types.
Scala has a '''Seq''' (for ''sequence'') trait that is more general than singly-linked lists. These two examples are equivalent for SLL, but the second would be faster for other sequence types.
<lang scala>def traverse1[T](xs: Seq[T]): Unit = xs match {

<lang scala>
def traverse1[T](xs: Seq[T]): Unit = xs match {
case s if s.isEmpty => ()
case s if s.isEmpty => ()
case _ => { Console.println(xs.head);
case _ => { Console.println(xs.head);
traverse1(xs.tail)
traverse1(xs.tail)
}
}
}</lang>
}
</lang>


<lang scala>def traverse2[T](xs: Seq[T]) = for (x <- xs) Console.println(x)</lang>
<lang scala>
def traverse2[T](xs: Seq[T]) = for (x <- xs) Console.println(x)
</lang>


=={{header|Scheme}}==
=={{header|Scheme}}==
Line 523: Line 474:
=={{header|Tcl}}==
=={{header|Tcl}}==
Using the class definition from [[Singly-Linked List (element)#Tcl|Singly-Linked List (element)]] (and bearing in mind the general notes on lists given there) we'll modify that class so that lists have an iteration method...
Using the class definition from [[Singly-Linked List (element)#Tcl|Singly-Linked List (element)]] (and bearing in mind the general notes on lists given there) we'll modify that class so that lists have an iteration method...
<br>
{{works with|Tcl|8.6}}
{{works with|Tcl|8.6}}
<lang tcl>oo::define List {
<lang tcl>oo::define List {
Line 549: Line 499:


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==

<lang vbnet>Private Sub Iterate(ByVal list As LinkedList(Of Integer))
<lang vbnet>Private Sub Iterate(ByVal list As LinkedList(Of Integer))
Dim node = list.First
Dim node = list.First

Revision as of 12:30, 23 September 2011

Task
Singly-linked list/Traversal
You are encouraged to solve this task according to the task description, using any language you may know.

Traverse from the beginning of a singly-linked list to the end.

ActionScript

See Singly-Linked List (element) in ActionScript <lang ActionScript>var A:Node; //... for(var i:Node = A; i != null; i = i.link) { doStuff(i); }</lang>

Ada

The Ada standard container library provides a doubly-linked list. List traversal is demonstrated for the forward links.

<lang ada>with Ada.Containers.Doubly_Linked_Lists; with Ada.Text_Io; use Ada.Text_Io;

procedure Traversal_Example is

  package Int_List is new Ada.Containers.Doubly_Linked_Lists(Integer);
  use Int_List;
  procedure Print(Position : Cursor) is
  begin
     Put_Line(Integer'Image(Element(Position)));
  end Print;
  The_List : List;

begin

  for I in 1..10 loop
     The_List.Append(I);
  end loop;
  -- Traverse the list, calling Print for each value
  The_List.Iterate(Print'access);

end traversal_example;</lang>

ALGOL 68

Works with: ALGOL 68 version Revision 1 - no extensions to language used
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny
Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8-8d

Linked lists are not built into ALGOL 68 per se, nor any available standard library. However Linked lists are presented in standard text book examples. Or can be manually constructed, eg: <lang algol68>MODE STRINGLIST = STRUCT(STRING value, REF STRINGLIST next);

STRINGLIST list := ("Big",

 LOC STRINGLIST := ("fjords",
   LOC STRINGLIST := ("vex",
     LOC STRINGLIST := ("quick",
       LOC STRINGLIST := ("waltz",
         LOC STRINGLIST := ("nymph",NIL))))));

REF STRINGLIST node := list; WHILE node ISNT REF STRINGLIST(NIL) DO

 print((value OF node, space));
 node := next OF node

OD; print(newline)</lang> Output:

Big fjords vex quick waltz nymph

AutoHotkey

<lang AutoHotkey>a = 1 a_next = b b = 2 b_next = c c = 3

traverse("a") return

traverse(element) {

 MsgBox % element . "= " . %element%
 name := element . "_next"
 while, %name%
 {
 element := %name%
 msgbox % %name% . "= " . %element%
 name := %name% . "_next"
 }

}</lang>

C

See Singly-Linked List (element) in C. <lang c>struct link *first; // ... struct link *iter; for(iter = first; iter != NULL; iter = iter->next) {

 // access data, e.g. with iter->data

}</lang>

C#

Simple iteration with a while loop. <lang csharp>//current is the first Link in the list while(current != null){

   System.Console.WriteLine(current.item);
   current = current.next;

}</lang>

Clojure

<lang lisp>(doseq [x xs] (println x)</lang>

Common Lisp

<lang lisp>(dolist (x list)

 (print x))</lang>

Not using builtin list iteration:

<lang lisp>(loop for ref = list then (rest ref)

     until (null ref)
     do (print (first ref)))</lang>

D

Traversal using list defined in Singly-Linked list element - D. <lang D>// a is a beginning of a list); while (a) {

   Stdout(a.data) (" -> ");
   a = a.next;

}</lang>

Or using tango's collections (written by Doug Lea, ported to D)

<lang D>import tango.io.Stdout; import tango.util.collection.LinkSeq;

void main() {

   auto m = new LinkSeq!(char[]);
   m.append("alpha");
   m.append("bravo");
   m.append("charlie");
   foreach (val; m)
       Stdout (val).newline;

}</lang>

Delphi

<lang delphi>uses system ;

type

  // declare the list pointer type
  plist = ^List ;

  // declare the list type, a generic data pointer prev and next pointers
  List = record
     data : pointer ;
     next : pList ;
  end;

// since this task is just showing the traversal I am not allocating the memory and setting up the root node etc. // Note the use of the carat symbol for de-referencing the pointer.

begin

  // beginning to end
  while not (pList^.Next = NIL) do pList := pList^.Next ;

end;</lang>

E

Using a list made from tuples: <lang e>var linkedList := [1, [2, [3, [4, [5, [6, [7, null]]]]]]]

while (linkedList =~ [value, next]) {

   println(value)
   linkedList := next

}</lang>

Using a list made from the structure defined at Singly-Linked List (element): <lang e>var linkedList := makeLink(1, makeLink(2, makeLink(3, empty)))

while (!(linkedList.null())) {

   println(linkedList.value())
   linkedList := linkedList.next()

}</lang>

Ela

<lang ela>let traverse [] = []

   traverse (x::xs) = x :: traverse xs</lang>

This function traverses a list and constructs a new list at the same time. For a list in Ela it is the same as identity function, e.g. traverse [1,2,3] == [1,2,3]. However it can be useful in some cases. For example, to enforce a lazy list:

<lang ela>let xs = [& x \\ x <- [1..1000]]//lazy list

traverse xs</lang>

Factor

<lang factor>: list-each ( linked-list quot: ( data -- ) -- )

   [ [ data>> ] dip call ]
   [ [ next>> ] dip over [ list-each ] [ 2drop ] if ] 2bi ; inline recursive

SYMBOLS: A B C ;

A <linked-list> [ C <linked-list> list-insert ] keep [ B <linked-list> list-insert ] keep

[ . ] list-each</lang> Output:

A
B
C

Fantom

Using the definitions from Singly-Linked_List_(element_insertion): <lang fantom> // traverse the linked list

   Node? current := a
   while (current != null)
   {
     echo (current.value)
     current = current.successor
   }</lang>

Forth

<lang forth>: last ( list -- end )

 begin dup @ while @ repeat ;</lang>

And here is a function to walk a list, calling an XT on each data cell: <lang forth>: walk ( a xt -- )

  >r begin ?dup while
    dup cell+ @ r@ execute
  @ repeat r> drop ;</lang>

Testing code:

A ' emit walk ABC ok

Go

See Singly-Linked List (element) in Go. <lang go>start := &Ele{"tacos", nil} end := start.Append("burritos") end = end.Append("fajitas") end = end.Append("enchilatas") for iter := start; iter != nil; iter = iter.Next {

   fmt.Println(iter)

}</lang>

Haskell

Lists are ubiquitous in Haskell, simply use Haskell's map library function: <lang haskell>map (>5) [1..10] -- [False,False,False,False,False,True,True,True,True,True]

map (++ "s") ["Apple", "Orange", "Mango", "Pear"] -- ["Apples","Oranges","Mangos","Pears"]

foldr (+) 0 [1..10] -- prints 55

traverse :: [a] -> [a] traverse list = map func list where func a = -- ...do something with a</lang>

Note that the traverse function is polymorphic; denoted by traverse :: [a] -> [a] where a can be of any type.

Icon and Unicon

Using either the record or class-based definitions from Singly-Linked List (element) in Icon and Unicon: <lang Icon>procedure main ()

 ns := Node(1, Node(2, Node (3)))
 until /ns do { # repeat until ns is null
   write (ns.value)
   ns := ns.successor
 }

end</lang> Prints the numbers 1, 2, 3 in turn.

J

Using the implementation mentioned at Singly-Linked List (element) in J, we can apply a function foo to each node the following way: <lang J>foo"0 {:"1 list</lang>

Java

Works with: Java version 1.5+

For Java.util.LinkedList<T>, use a for each loop (from Loop Structures): <lang java>LinkedList<Type> list = new LinkedList<Type>();

for(Type i: list){

 //each element will be in variable "i"
 System.out.println(i);

}</lang> Note that java.util.LinkedList can also perform as a stack, queue, or doubly-linked list.

JavaScript

Extending Singly-Linked_List_(element)#JavaScript <lang javascript>LinkedList.prototype.traverse = function(func) {

   func(this);
   if (this.next() != null)
       this.next().traverse(func);

}

LinkedList.prototype.print = function() {

   this.traverse( function(node) {print(node.value())} );

}

var head = createLinkedListFromArray([10,20,30,40]); head.print();</lang> Uses the print() function from Rhino

LAST is already a Logo built-in, but it could be defined this way: <lang logo>to last :list

 if empty? bf :list [output first :list]
 output last bf :list

end</lang>

Objective-C

(See Singly-Linked List (element)) <lang objc>RCListElement *current; for(current=first_of_the_list; current != nil; current = [current next] ) {

 // to get the "datum":
 // id dat_obj = [current datum];

}</lang>

OCaml

<lang ocaml># let li = ["big"; "fjords"; "vex"; "quick"; "waltz"; "nymph"] in

 List.iter print_endline li ;;

big fjords vex quick waltz nymph - : unit = ()</lang>

Perl 6

Built-in list processing in Perl is not specifically based on singly-linked lists, but works at a higher abstraction level that encapsulates such implementation choices. Nonetheless, it's trivial to use the Pair type to build what is essentially a Lisp-style cons list, and in fact, the => pair constructor is right associative for precisely that reason. We traverse such a list here using a 3-part loop: <lang perl6>my $list = 1 => 2 => 3 => 4 => 5 => 6 => Mu;

loop (my $l = $list; $l; $l = $l.value) {

   say $l.key;

}</lang> Output:

1
2
3
4
5
6

It would be pretty easy to make such lists iterable as normal Perl lists, if anyone really cared to...

Well, shoot, let's just go ahead and do it. We'll pretend the Pair type is really a list type. (And we show how you turn an ordinary list into a cons list using a reduction. Note how the [=>] reduction is also right associative, just like the base operator.) <lang perl6>use MONKEY_TYPING; augment class Pair {

   method traverse () {
       gather loop (my $l = self; $l; $l = $l.value) {
           take $l.key;
       }
   }

}

my $list = [=>] 'Ⅰ' .. 'Ⅻ', Mu; say ~$list.traverse;</lang>

Output:

Ⅰ Ⅱ Ⅲ Ⅳ Ⅴ Ⅵ Ⅶ Ⅷ Ⅸ Ⅹ Ⅺ Ⅻ

PicoLisp

We might use map functions <lang PicoLisp>(mapc println '(a "cde" (X Y Z) 999))</lang> or flow control functions <lang PicoLisp>(for X '(a "cde" (X Y Z) 999)

  (println X) )</lang>

Output in both cases:

a
"cde"
(X Y Z)
999

Protium

This makes a list of the Chinese Public Holiday and lists them first till last and then last till first. <lang html><@ LETCNSLSTLIT>public holidays|開國紀念日^和平紀念日^婦女節、兒童節合併假期^清明節^國慶日^春節^端午節^中秋節^農曆除夕</@> <@ OMT>From First to Last</@> <@ ITEFORSZELSTLIT>public holidays| <@ SAYLST>...</@><@ ACTMOVFWDLST>...</@> </@> <@ OMT>From Last to First (pointer is still at end of list)</@> <@ ITEFORSZELSTLIT>public holidays| <@ SAYLST>...</@><@ ACTMOVBKWLST>...</@> </@></lang> This variable length Simplified Chinese rendition of the same code is <lang html><# 指定构造列表字串>public holidays|開國紀念日^和平紀念日^婦女節、兒童節合併假期^清明節^國慶日^春節^端午節^中秋節^農曆除夕</#> <# 忽略>From First to Last</#> <# 迭代迭代次数结构大小列表字串>public holidays| <# 显示列表>...</#><# 运行移位指针向前列表>...</#> </#> <# 忽略>From Last to First (pointer is still at end of list)</#> <# 迭代迭代次数结构大小列表字串>public holidays| <# 显示列表>...</#><# 运行移位指针向后列表>...</#> </#></lang>

PureBasic

<lang PureBasic>Procedure traverse(*node.MyData)

 While *node
   ;access data, i.e. PrintN(Str(*node\Value)) 
   *node = *node\next
 Wend

EndProcedure

called using

traverse(*firstnode.MyData)</lang>

Python

<lang python>for node in lst:

   print node.value</lang>

Any Python class can define next() and __iter__() methods so that it can be used with the normal for iteration syntax. In this example the "lst" could be an instance of any Python list, tuple, dictionary, or any sort of object which defines an iterator. It could also be a generator (a type of function which yields results upon each successive invocation). The notion of a "singly linked list" is somewhat more primitive than normal Python built-in objects. <lang python>class LinkedList(object):

 """USELESS academic/classroom example of a linked list implemented in Python.
    Don't ever consider using something this crude!  Use the built-in list() type!
 """
 def __init__(self, value, next):
   self.value = value;
   self.next = next
 def __iter__(self):
   node = self
   while node != None:
     yield node.value
     node = node.next;

lst = LinkedList("big", next=

 LinkedList(value="fjords",next=
   LinkedList(value="vex",   next=
     LinkedList(value="quick", next=
       LinkedList(value="waltz", next=
         LinkedList(value="nymph", next=None))))));

for value in lst:

 print value,;

print</lang> Output:

big fjords vex quick waltz nymph

Retro

<lang Retro>: traverse ( l- ) repeat @ 0; again ;</lang> Or, using combinators: <lang Retro>last [ drop ] ^types'LIST each@</lang> With combinators you can also perform an operation on each element in a linked list: <lang Retro>last [ @d->name puts space ] ^types'LIST each@</lang>

Ruby

referring to Singly-Linked List (element)#Ruby and Singly-Linked List (element insertion)#Ruby <lang ruby>head = ListNode.new("a", ListNode.new("b", ListNode.new("c"))) head.insertAfter("b", "b+")

  1. then:

head.each {|node| print node.value, ","} puts

  1. or

current = head begin

 print current.value, ","

end while current = current.succ puts</lang>

a,b,b+,c,
a,b,b+,c,

Scala

Scala has a Seq (for sequence) trait that is more general than singly-linked lists. These two examples are equivalent for SLL, but the second would be faster for other sequence types. <lang scala>def traverse1[T](xs: Seq[T]): Unit = xs match {

 case s if s.isEmpty => ()                    
 case _ => { Console.println(xs.head);        
             traverse1(xs.tail)
 }

}</lang>

<lang scala>def traverse2[T](xs: Seq[T]) = for (x <- xs) Console.println(x)</lang>

Scheme

<lang scheme>(define (traverse seq func)

 (if (null? seq)
     '()
     (begin
       (func (car seq))
       (traverse (cdr seq) func))))</lang>

Tcl

Using the class definition from Singly-Linked List (element) (and bearing in mind the general notes on lists given there) we'll modify that class so that lists have an iteration method...

Works with: Tcl version 8.6

<lang tcl>oo::define List {

   method for {varName script} {
       upvar 1 $varName var
       set elem [self]
       while {$elem ne ""} {
           set var [$elem value]
           uplevel 1 $script
           set elem [$elem next]
       }
   }

}</lang> Now, a demonstration... <lang tcl>set list {} foreach n {1 3 5 7 2 4 6 8} {

   set list [List new $n $list]

} $list for x {

   puts "we have a $x in the list"

}</lang>

Trith

<lang trith>[1 2 3 4 5] [print] each</lang>

Visual Basic .NET

<lang vbnet>Private Sub Iterate(ByVal list As LinkedList(Of Integer))

   Dim node = list.First
   Do Until node Is Nothing
       node = node.Next
   Loop
   End Sub</lang>