本文共 4225 字,大约阅读时间需要 14 分钟。
////// 节点类 /// ///
class Node{ private T date; //数据域 private Node next;//指针域 public T Date { get => date; set => date = value; } internal Node Next { get => next; set => next = value; } public Node() { Next = null; Date = default(T); } public Node(T date,Node next) { this.Date = date; this.Next = next; } public Node(T date) { Next = null; this.Date = date; } public Node(Node next) { this.Date = default(T); this.Next = next; } }
////// 链表类 /// class LinkList{ private Node head; //头指针 private int count; //链表元素个数 public LinkList() { head=new Node ();//指向头结点 count = 0; } //尾插法创建链表 public LinkList(params T[] list):this() { Node last = head; for (int i = 0; i < list.Length; i++) { Node newNode = new Node (list[i]); last.Next = newNode; last = last.Next; } count = list.Length; } //遍历单链表的元素 public void Traverse() { Node temp = head; for (int i = 0; i < count; i++) { temp = temp.Next; Console.Write(temp.Date+" "); } Console.WriteLine(); }
//判断是否为空 public bool IsEmepty() { return head.Next == null; } //获取链表长度 public int GetLength() { return count; }
//获取元素索引位置 public int Index(T elem) { Nodetemp = head; for (int i = 0; i < count; i++) { temp = temp.Next; if (temp.Date.Equals(elem)) { return i; } } Console.WriteLine("elem:{0}不在链表中", elem); return -1; }
//通过索引器获取元素 public T this[int index] { get { if (index>=count||index<0) { throw new IndexOutOfRangeException(); } Nodetemp = head; for (int i = 0; i <=index; i++) { temp = temp.Next; } return temp.Date; } }
//插入元素 public void Insert(int index,T elem) { Nodetemp = head; Node newNode=new Node (elem,null); if (index >= count || index < 0) { throw new IndexOutOfRangeException(); } //当为空链表的时候 if (temp.Next == null) { temp.Next = newNode; count++; } else { for (int i = 0; i < index; i++) { temp = temp.Next; } newNode.Next = temp.Next; temp.Next = newNode; count++; } }
//删除元素 public void Delete(int index) { Nodetemp = head; if (head.Next == null) { Console.WriteLine("空表无法删除"); } if (index >= count || index < 0) { throw new IndexOutOfRangeException(); } for (int i = 0; i < index; i++) { temp = temp.Next; } temp.Next = temp.Next.Next; count--; } }
LinkList sum=new LinkList (1,2,5,8,5,888,555); sum.Traverse(); Console.WriteLine(sum.IsEmepty()); Console.WriteLine(sum.GetLength()); Console.WriteLine(sum.Index(8)); Console.WriteLine(sum[6]); //sum.Insert(2, 120); //sum.Traverse(); sum.Delete(100); sum.Traverse(); Console.ReadKey();
转载地址:http://vdrxo.baihongyu.com/