/// <summary> /// 以一个数组为参数,构造一个链表 /// </summary> /// <param name="source"></param> public LinkList(object[] source) { LinkListNode current; current = head; for (int i = 0; i < source.Length; i++) { LinkListNode newNode = new LinkListNode(); newNode.data = source[i]; current.next = newNode; current = newNode; } current.next = null; tail = current; }
private int GetCount() { int count = -1; //之所以等于-1.是因为这里的单链表都是包含“头指针”的, LinkListNode p = head; //而头指针只包含一个指向第一节点的指针,并不包含内容 if (p == null) { return(0); } else { while (p != null) { count++; p = p.next; } return(count); } }
public void Print() { string info = ""; LinkListNode p = head.next; if (p == null) { info = "该链表是一个空链表"; } else { while (p != null) { info += p.data + " "; p = p.next; } } Console.WriteLine(info); }
/// <summary> /// 删除某一个位置的元素 /// </summary> /// <param name="index"></param> public void DeleteAt(int index) { LinkListNode p = head.next; if (index > Count) { throw new Exception("要删除的元素在链表之外!"); } else { int searchIndex = 1; while (searchIndex != index) { p = p.next; searchIndex++; } LinkListNode q = p.next; if (q != null) { p.next = q.next; q = null; } } }
/// <summary> /// 构造函数,构造无参数的构造函数,即一个空链表 /// </summary> public LinkList() { head.next = null; tail = head; //没有元素的时候,头结点和尾节点是一个 }