Doubly-linked list/Traversal: Difference between revisions
Content added Content deleted
(Created page with '{{task|Data Structures}}Category:Iteration Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning.') |
(add JavaScript) |
||
Line 1: | Line 1: | ||
{{task|Data Structures}}[[Category:Iteration]] |
{{task|Data Structures}}[[Category:Iteration]] |
||
Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. |
Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. |
||
=={{header|JavaScript}}== |
|||
See [[Doubly-Linked_List_(element)#JavaScript]]. The <code>traverse()</code> and <code>print()</code> functions have been inherited from [[Singly-Linked_List_(traversal)#JavaScript]]. |
|||
<lang javascript>DoublyLinkedList.prototype.getTail = function() { |
|||
var tail; |
|||
this.traverse(function(node){tail = node;}); |
|||
return tail; |
|||
} |
|||
DoublyLinkedList.prototype.traverseBackward = function(func) { |
|||
func(this); |
|||
if (this.prev() != null) |
|||
this.prev().traverseBackward(func); |
|||
} |
|||
DoublyLinkedList.prototype.printBackward = function() { |
|||
this.traverseBackward( function(node) {print(node.value())} ); |
|||
} |
|||
var head = createDoublyLinkedListFromArray([10,20,30,40]); |
|||
head.print(); |
|||
head.getTail().printBackward();</lang> |
|||
outputs: |
|||
<pre>10 |
|||
20 |
|||
30 |
|||
40 |
|||
40 |
|||
30 |
|||
20 |
|||
10</pre> |
|||
Uses the <code>print()</code> function from [[Rhino]] or [[SpiderMonkey]]. |
Revision as of 14:45, 9 October 2009
Doubly-linked list/Traversal
You are encouraged to solve this task according to the task description, using any language you may know.
You are encouraged to solve this task according to the task description, using any language you may know.
Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning.
JavaScript
See Doubly-Linked_List_(element)#JavaScript. The traverse()
and print()
functions have been inherited from Singly-Linked_List_(traversal)#JavaScript.
<lang javascript>DoublyLinkedList.prototype.getTail = function() {
var tail; this.traverse(function(node){tail = node;}); return tail;
} DoublyLinkedList.prototype.traverseBackward = function(func) {
func(this); if (this.prev() != null) this.prev().traverseBackward(func);
} DoublyLinkedList.prototype.printBackward = function() {
this.traverseBackward( function(node) {print(node.value())} );
}
var head = createDoublyLinkedListFromArray([10,20,30,40]); head.print(); head.getTail().printBackward();</lang>
outputs:
10 20 30 40 40 30 20 10
Uses the print()
function from Rhino or SpiderMonkey.