fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace LinkedList {
  8. class LinkedList<T> {
  9. public LinkedList() {
  10. this.head = null;
  11. }
  12.  
  13. public void Add(T obiekt) {
  14. Element newElement = new Element(obiekt);
  15. if (this.head == null) {
  16. this.head = newElement;
  17. this.head.next = this.head;
  18. this.head.prev = this.head;
  19. this.head.last = this.head;
  20. }
  21. else {
  22. this.head.last.next = newElement;
  23. newElement.prev = this.head.last;
  24. this.head.last = newElement;
  25. newElement.next = this.head;
  26. this.head.prev = newElement;
  27. }
  28. }
  29.  
  30. public void Print() {
  31. Element temp = this.head;
  32. do {
  33. Console.WriteLine(temp.obj.ToString());
  34. temp = temp.next;
  35. } while (temp != this.head);
  36. }
  37.  
  38. /// <summary>
  39. /// Przy usuwaniu po prostu ustawiamy usuwaną referencję na null.
  40. /// GC zajmie się resztą. Ewentualnie można zaimplementować interfejs IDisposable
  41. /// dla klasy Element i wywoływać ręcznie metodę dispose.
  42. /// </summary>
  43. public void Remove(T obiekt) {
  44. Element temp = this.head;
  45. Element forDel = null;
  46.  
  47. do {
  48. if (temp.obj.Equals(obiekt)) {
  49. forDel = temp;
  50. temp.prev.next = temp.next;
  51. temp.next.prev = temp.prev;
  52. if (temp == this.head) this.head = temp.next;
  53. forDel = null;
  54. break;
  55. }
  56. else temp = temp.next;
  57.  
  58. } while (temp != this.head);
  59. }
  60.  
  61. private Element head;
  62. private class Element {
  63. public Element(T obiekt) {
  64. this.obj = obiekt;
  65. this.next = null;
  66. this.prev = null;
  67. this.last = null;
  68. }
  69.  
  70. public T obj { get; set; }
  71. public Element next { get; set; }
  72. public Element prev { get; set; }
  73. public Element last { get; set; }
  74. }
  75. }
  76.  
  77. class Program {
  78. static void Main(string[] args) {
  79. LinkedList<string> lista = new LinkedList<string>();
  80. lista.Add("Grzegorz");
  81. lista.Add("Tomasz");
  82. lista.Add("Zbyszek");
  83. lista.Add("Marcin");
  84. lista.Remove("Marcin");
  85. lista.Print();
  86. Console.ReadKey();
  87. }
  88. }
  89. }
  90.  
Success #stdin #stdout 0.03s 24184KB
stdin
Standard input is empty
stdout
Grzegorz
Tomasz
Zbyszek