Singly-linked list/Traversal: Difference between revisions

From Rosetta Code
Content added Content deleted
(Simplify iteration)
(None won't work now as empty list)
Line 40: Line 40:
==[[Python]]==
==[[Python]]==
[[Category:Python]]
[[Category:Python]]

lst is either None (the empty list) or a Node instance connected to the next node.


<pre>
<pre>

Revision as of 16:22, 4 November 2007

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

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