fork download
  1. using static System.Console;
  2.  
  3. public class Node<T> {
  4. public T Value { get; set; }
  5. public Node<T> Next { get; set; }
  6. }
  7.  
  8. public class LinkedList<T> {
  9. private Node<T> head = null;
  10.  
  11. public Node<T> Add(T value) {
  12. var node = new Node<T> {Value = value};
  13. if (head == null) head = node;
  14. else {
  15. var current = head;
  16. while (current.Next != null) current = current.Next;
  17. current.Next = node;
  18. }
  19. return node;
  20. }
  21.  
  22. public T Remove(Node<T> node) {
  23. if (head == null) return node.Value;
  24. if (head == node) {
  25. head = head.Next;
  26. node.Next = null;
  27. return node.Value;
  28. }
  29. var current = head;
  30. while (current.Next != null) {
  31. if (current.Next == node) {
  32. current.Next = node.Next;
  33. return node.Value;
  34. }
  35. current = current.Next;
  36. }
  37. return node.Value;
  38. }
  39.  
  40. public void Print() {
  41. var current = head;
  42. while (current != null) {
  43. WriteLine(current.Value);
  44. current = current.Next;
  45. }
  46. }
  47. }
  48.  
  49. public class Program {
  50. public static void Main(string[] args) {
  51. var ll = new LinkedList<int>();
  52. var node1 = ll.Add(1);
  53. var node2 = ll.Add(2);
  54. var node3 = ll.Add(3);
  55. var node4 = ll.Add(4);
  56. var node5 = ll.Add(5);
  57. ll.Print();
  58. WriteLine();
  59. ll.Remove(node3);
  60. ll.Print();
  61. }
  62. }
  63.  
  64. //https://pt.stackoverflow.com/q/164085/101
Success #stdin #stdout 0.02s 15948KB
stdin
Standard input is empty
stdout
1
2
3
4
5

1
2
4
5