OK, here's a rough example of how you can implement a linked list in C#.
Code:namespace LinkedListExample { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Element[] elements = new Element[3]; for (int i = 0; i < elements.Length; ++i) { elements[i] = new Element(); elements[i].Value = "val" + i.ToString(); } MyLinkedList ll = new MyLinkedList(); foreach (Element e in elements) ll.Add(e); for (int i = 0; i < ll.Count; ++i) Console.WriteLine(ll[i].Value); // prints out: val0, val1, val2 } } public class Element { public string Value { get; set; } public Element Next { get; set; } } public class MyLinkedList { private Element head = null; public int Count { get; private set; } public void Add(Element item) // see, no ref keyword required, as long as Element is class, instead of a struct { if (head == null) head = item; else { Element last = head; while (last.Next != null) last = last.Next; last.Next = item; } Count++; } public Element this[int i] // indexer { get { int k = 0; Element current = head; while (k < Count) { if (i == k) return current; current = current.Next; k++; } return null; } // you can implement set... } } }




Reply With Quote