Singly-linked list/Traversal: Difference between revisions
Content added Content deleted
(Replace article on iteration with simple transversal code) |
(Simplify iteration) |
||
Line 41: | Line 41: | ||
[[Category:Python]] |
[[Category:Python]] |
||
lst is either None (the empty list) or Node connected to the next node. |
lst is either None (the empty list) or a Node instance connected to the next node. |
||
<pre> |
<pre> |
||
lst = Node('A', Node('B')) |
|||
while lst is not None: |
|||
for node in lst: |
|||
print node.value |
|||
</pre> |
|||
For more Pythonic iteration, you can use a genertor function: |
|||
<pre> |
|||
def iternode(lst): |
|||
while lst is not None: |
|||
yield lst |
|||
lst = lst.next |
|||
</pre> |
</pre> |
Revision as of 16:04, 4 November 2007
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
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 is either None (the empty list) or a Node instance connected to the next node.
lst = Node('A', Node('B')) for node in lst: print node.value