Doubly-linked list/Traversal: Difference between revisions
Content added Content deleted
m (PL/I code moved to its correct alphabetical position.) |
|||
Line 897: | Line 897: | ||
: (2printReversed *DL) # Print it in reversed order |
: (2printReversed *DL) # Print it in reversed order |
||
B C A</pre> |
B C A</pre> |
||
=={{header|PL/I}}== |
|||
<lang PL/I>/* To implement a doubly-linked list -- i.e., a 2-way linked list. */ |
|||
doubly_linked_list: proc options (main); |
|||
define structure |
|||
1 node, |
|||
2 value fixed, |
|||
2 fwd_pointer handle(node), |
|||
2 back_pointer handle(node); |
|||
declare (head, tail, t) handle (node); |
|||
declare null builtin; |
|||
declare i fixed binary; |
|||
head, tail = bind(:node, null:); |
|||
do i = 1 to 10; /* Add ten items to the tail of the queue. */ |
|||
if head = bind(:node, null:) then |
|||
do; |
|||
head,tail = new(:node:); |
|||
get list (head => value); |
|||
put skip list (head => value); |
|||
head => back_pointer, |
|||
head => fwd_pointer = bind(:node, null:); /* A NULL link */ |
|||
end; |
|||
else |
|||
do; |
|||
t = new(:node:); |
|||
t => back_pointer = tail; /* Point the new tail back to the old */ |
|||
/* tail. */ |
|||
tail => fwd_pointer = t; /* Point the tail to the new node. */ |
|||
t => back_pointer = tail; /* Point the new tail back to the old */ |
|||
/* tail. */ |
|||
tail = t; /* Point at teh new tail. */ |
|||
tail => fwd_pointer = bind(:node, null:); |
|||
/* Set the tail link to NULL */ |
|||
get list (tail => value) copy; |
|||
put skip list (tail => value); |
|||
end; |
|||
end; |
|||
if head = bind(:node, null:) then return; /* Empty list. */ |
|||
/* Traverse the list from the head. */ |
|||
put skip list ('In a forwards direction, the list has:'); |
|||
t = head; |
|||
do while (t ^= bind(:node, null:)); |
|||
put skip list (t => value); |
|||
t = t => fwd_pointer; |
|||
end; |
|||
/* Traverse the list from the tail to the head. */ |
|||
put skip list ('In the reverse direction, the list has:'); |
|||
t = tail; |
|||
do while (t ^= bind(:node, null:)); |
|||
put skip list (t => value); |
|||
t = t => back_pointer; |
|||
end; |
|||
end doubly_linked_list;</lang> |
|||
Output: |
|||
<pre> |
|||
In a forwards direction, the list has: |
|||
1 |
|||
2 |
|||
3 |
|||
4 |
|||
5 |
|||
16 |
|||
7 |
|||
8 |
|||
9 |
|||
10 |
|||
In the reverse direction, the list has: |
|||
10 |
|||
9 |
|||
8 |
|||
7 |
|||
16 |
|||
5 |
|||
4 |
|||
3 |
|||
2 |
|||
1</pre> |
|||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |