A response to the question
"Questions every good .NET developer should be able to answer?" on StackOverflow was
"Write your own linked list class without using the built-in classes".
I hadn't done this in quite a while (I'd done it in C++ years ago), so I gave it a try off the top of my head. Here's my first pass, using just the
Wikipedia entry, vim, and the compiler.
Yes, I realize there's little practical point to this; I'm sure the person posting the response on StackOverflow does too. It's just an exercise.
using System;
namespace RootSilver {
public class LinkedList<T> {
//Node(data, pointer to next) --> Node(data, null)
//see http://en.wikipedia.org/wiki/Linked_list
private class Node {
public Node<T> Next{ get; set; }
public T Value{ get; private set;}
public Node(){}
public Node(T data) {
this.Value = data;
}
}
private Node<T> currentNode;
private Node<T> headNode; //placeholder/anchor
public bool End() {
return this.currentNode == null;
}
public void Remove(int position) {
var node = this.headNode;
//walk the list until we find the postion
int i = 0;
while( i < position - 1 ) {
node = node.Next;
++i;
}
node.Next = node.Next.Next ?? null;
}
public void Insert(T data, int position) {
var node = this.headNode;
int i = 0;
while( i < position - 1 ) {
node = node.Next;
++i;
}
var newNode = new Node(data);
newNode.Next = node.Next;
node.Next = newNode;
}
public void Add(T data) {
var node = new Node<T>(data);
if(this.headNode == null) {
this.headNode = node;
} else {
this.currentNode.Next = node;
}
this.currentNode = node;
}
public T Value {
get{ return this.currentNode.Value; }
}
public T First(){
this.currentNode = this.headNode;
return this.currentNode.Value;
}
public T Next() {
//stop at last & go no further (I'm stuck!!)
T data = this.currentNode.Value;
this.currentNode = this.currentNode.Next;
return data;
}
}
public class Test {
public static void Main() {
var list = new LinkedList();
for(int i = 0; i < 5; i++)
list.Add(i.ToString());
Console.WriteLine("\n--------Output-----------------");
list.First();
while( ! list.End() ) {
Console.WriteLine("Next:" + list.Value.ToString());
list.Next();
}
Console.WriteLine("\n--------Insert Bob at 3 -------");
list.Insert("bob", 3);
list.First();
while( ! list.End() ) {
Console.WriteLine("Next:" + list.Value.ToString());
list.Next();
}
Console.WriteLine("\n--------Remove-----------------");
list.Remove(3);
list.First();
while( ! list.End() ) {
Console.WriteLine("Next:" + list.Value.ToString());
list.Next();
}
}
}
}