using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinkedList {
class LinkedList<T> {
public LinkedList() {
this.head = null;
}
public void Add(T obiekt) {
Element newElement = new Element(obiekt);
if (this.head == null) {
this.head = newElement;
this.head.next = this.head;
this.head.prev = this.head;
this.head.last = this.head;
}
else {
this.head.last.next = newElement;
newElement.prev = this.head.last;
this.head.last = newElement;
newElement.next = this.head;
this.head.prev = newElement;
}
}
public void Print() {
Element temp = this.head;
do {
Console.WriteLine(temp.obj.ToString());
temp = temp.next;
} while (temp != this.head);
}
/// <summary>
/// Przy usuwaniu po prostu ustawiamy usuwaną referencję na null.
/// GC zajmie się resztą. Ewentualnie można zaimplementować interfejs IDisposable
/// dla klasy Element i wywoływać ręcznie metodę dispose.
/// </summary>
public void Remove(T obiekt) {
Element temp = this.head;
Element forDel = null;
do {
if (temp.obj.Equals(obiekt)) {
forDel = temp;
temp.prev.next = temp.next;
temp.next.prev = temp.prev;
if (temp == this.head) this.head = temp.next;
forDel = null;
break;
}
else temp = temp.next;
} while (temp != this.head);
}
private Element head;
private class Element {
public Element(T obiekt) {
this.obj = obiekt;
this.next = null;
this.prev = null;
this.last = null;
}
public T obj { get; set; }
public Element next { get; set; }
public Element prev { get; set; }
public Element last { get; set; }
}
}
class Program {
static void Main(string[] args) {
LinkedList<string> lista = new LinkedList<string>();
lista.Add("Grzegorz");
lista.Add("Tomasz");
lista.Add("Zbyszek");
lista.Add("Marcin");
lista.Remove("Marcin");
lista.Print();
Console.ReadKey();
}
}
}