Skip to content

Instantly share code, notes, and snippets.

@alphaKAI
Created March 19, 2015 01:42
Show Gist options
  • Select an option

  • Save alphaKAI/c5a97def2ccaa2221832 to your computer and use it in GitHub Desktop.

Select an option

Save alphaKAI/c5a97def2ccaa2221832 to your computer and use it in GitHub Desktop.
Simple LinkedList written in D
import std.stdio;
class ListNode(T){
ListNode!T nextNode,
prevNode;
T value;
this(T arg){
value = arg;
}
}
class List(T){
alias ListNode!T Node;
Node firstNode,
lastNode,
thisNode;
this(T arg){
firstNode = lastNode = new Node(arg);
}
void addNode(Node newNode){
if(lastNode !is null){
lastNode.nextNode = newNode;
newNode.prevNode = lastNode;
lastNode = newNode;
} else {
firstNode = lastNode = newNode;
newNode.prevNode = null;
}
}
void addNode(T newValue){
Node newNode = new Node(newValue);
this.addNode(newNode);
}
void printAll(){
for(thisNode = firstNode; thisNode !is null; thisNode = thisNode.nextNode){
thisNode.value.writeln;
}
}
void printReAll(){
for(thisNode = lastNode; thisNode !is null; thisNode = thisNode.prevNode){
thisNode.value.writeln;
}
}
bool findNode(T key){
for(thisNode = firstNode; thisNode !is null; thisNode = thisNode.nextNode)
if(thisNode.value == key)
return true;
return false;
}
Node pickupNode(T key){
Node reNode;
for(thisNode = firstNode; thisNode !is null; thisNode = thisNode.nextNode)
if(thisNode.value == key)
reNode = thisNode;
return reNode;
}
T[] toArray(){
T[] tArray;
for(thisNode = firstNode; thisNode !is null; thisNode = thisNode.nextNode)
tArray ~= thisNode.value;
return tArray;
}
T[] toReArray(){
T[] tArray;
for(thisNode = lastNode; thisNode !is null; thisNode = thisNode.prevNode)
tArray ~= thisNode.value;
return tArray;
}
}
void main(){
List!int intList = new List!int(1);
intList.addNode(2);
intList.addNode(3);
intList.addNode(4);
//test
foreach(i; 1..5){
assert(intList.findNode(i));
assert(intList.pickupNode(i).value == new ListNode!int(i).value);//Need to more consideration
}
assert(intList.toArray == [1, 2, 3, 4]);
assert(intList.toReArray == [4, 3, 2, 1]);
intList.printAll;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment