Linked List Iterator (foreach)
Mason Green
mason.green at gmail.com
Tue Aug 19 11:35:26 PDT 2008
Hello, D world.
I've finally gotten around to experimenting with Templates, and was wondering if anyone knows of a simple way to implement a linked list iterator.... Ideally I would like iterate through the list using foreach...
Here's what I have so far.... Any help would be appreciated....
class FastCell(T) {
T elt;
FastCell!(T) next;
this(T elt, FastCell!(T) next) {
this.elt = elt;
this.next = next;
}
}
/**
A linked-list of elements.
**/
class FastList(T) {
alias FastCell!(T) Fast;
Fast head;
/**
Creates a new empty list.
**/
this() {
head = null;
}
/**
Add an element at the head of the list.
**/
void add(T item) {
head = new Fast(item, head);
}
/**
Returns the first element of the list, or null
if the list is empty.
**/
T first() {
return (head is null ? null : head.elt);
}
/**
Removes the first element of the list and
returns it or simply returns null if the
list is empty.
**/
T pop() {
Fast k = head;
if( k is null )
return null;
else {
head = k.next;
return k.elt;
}
}
/**
Tells if a list is empty.
**/
bool isEmpty() {
return (head is null);
}
/**
Remove the first element that is [== v] from the list.
Returns [true] if an element was removed, [false] otherwise.
**/
bool remove(T v) {
Fast prev = null;
Fast l = head;
while( l !is null ) {
if( l.elt == v ) {
if( prev is null )
head = l.next;
else
prev.next = l.next;
break;
}
prev = l;
l = l.next;
}
return (l !is null);
}
}
More information about the Digitalmars-d-learn
mailing list