Singly-linked list/Traversal: Difference between revisions

From Rosetta Code
Content added Content deleted
m (Can't have two task templates on one page)
(add Ruby)
Line 170: Line 170:
</pre>
</pre>


=={{header|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+")


# then:
head.each {|value| print value, ","}
puts

# or
current = head
while current
print current.value, ","
current = current.succ
end
puts</lang>
<pre>a,b,b+,c,
a,b,b+,c,</pre>
=={{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...

Revision as of 07:26, 12 June 2009

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.

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

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:

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 REF STRINGLIST(node) ISNT NIL DO
  print((value OF node, space));
  node := next OF node
OD;
print((newline))

Output:

Big fjords vex quick waltz nymph 

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>

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>

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

Java

Works with: Java version 1.5+

For Java.util.LinkedList<T>, use a for each loop (from Loop Structures):

LinkedList<Type> list = new LinkedList<Type>();

for(Type i: list){
  //each element will be in variable "i"
  System.out.println(i);
}

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

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>

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):

 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

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 {|value| print value, ","} puts

  1. or

current = head while current

 print current.value, ","
 current = current.succ

end puts</lang>

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

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>

Visual Basic .NET

   Private Sub Iterate(ByVal list As LinkedList(Of Integer))
       Dim node = list.First
       Do Until node Is Nothing
           node = node.Next
       Loop
   End Sub