首页 > 代码库 > 单链表的C#实现

单链表的C#实现

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace Algorithm {
  7. class MyListNode<T> {
  8. public T Key { get; set; }
  9. public MyListNode<T> Next { get; set; }
  10. public MyListNode(T k) {
  11. Key = k;
  12. }
  13. }
  14. class MyList<T> {
  15. private MyListNode<T> head;
  16. public MyListNode<T> Head {
  17. get {return head;}
  18. set {head = value;}
  19. }
  20. public MyList(){
  21. head = null;
  22. }
  23. public void Walk(MyListNode<T> headNode,Action<T> act) {
  24. MyListNode<T> node = headNode;
  25. while (node != null) {
  26. act(node.Key);
  27. node = node.Next;
  28. }
  29. }
  30. public MyListNode<T> Add(T key) {
  31. MyListNode<T> newNode = new MyListNode<T>(key);
  32. if (head == null) {
  33. head = newNode;
  34. } else {
  35. MyListNode<T> node = head;
  36. while (node.Next != null) {
  37. node = node.Next;
  38. }
  39. node.Next = newNode;
  40. }
  41. return newNode;
  42. }
  43. public void Add(T[] keys) {
  44. foreach (var i in keys) {
  45. Add(i);
  46. }
  47. }
  48. public void Delete(MyListNode<T> node) {
  49. node.Key = node.Next.Key;
  50. node.Next = node.Next.Next;
  51. }
  52. //翻转
  53. public MyListNode<T> Rverse(MyListNode<T> head) {
  54. if (head == null || head.Next == null)
  55. return head;
  56. MyListNode<T> nextNode = head.Next;
  57. MyListNode<T> newHead = Rverse(nextNode);
  58. nextNode.Next = head;
  59. head.Next = null;
  60. return newHead;
  61. }
  62. //寻找中间节点
  63. public MyListNode<T> FindMid(MyListNode<T> head) {
  64. MyListNode<T> fast = head;
  65. MyListNode<T> slow = head;
  66. while (fast != null) {
  67. if (fast.Next != null) {
  68. fast = fast.Next.Next;
  69. } else {
  70. break;
  71. }
  72. slow = slow.Next;
  73. }
  74. return slow;
  75. }
  76. }
  77. }



null


单链表的C#实现