Singly-linked list/Traversal

From Rosetta Code
Revision as of 18:59, 19 February 2008 by rosettacode>Mwn3d (→‎{{header|Java}}: Changed over to works with template)
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.

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;


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.

Python

lst = Node('A', Node('B'))
for node in lst:
    print node.value