public class LinkedList { private class Node { public Node(object value) { item = value; } public object item;//数据域 public LinkedList.Node next;//指针域 public override string ToString() { return item.ToString(); } } private int count;//记录元素个数 public int Count { get { return count; } } private Node head;//头指针 public object this[int index]//索引器 { get { return GetByIndex(index).item; } set { GetByIndex(index).item = value; } } //添加元素 public void Add(object value) { Node newNode = new Node(value); if (head == null) head = newNode; else { GetByIndex(count - 1).next = newNode; } count++; } //在指定索引处插入元素 public void Insert(int index, object value) { Node tempNode; if (index == 0) { if (head == null) { tempNode = new Node(value); head = tempNode; } else { tempNode = new Node(value); Node next = head.next; head.next = tempNode; tempNode.next = next; } } else { Node preNode = GetByIndex(index - 1);//找插入节点的前驱 Node next = preNode.next;//找插入节点的后驱 tempNode = new Node(value); preNode.next = tempNode; tempNode.next = next; } count++; } public void RemoveAt(int index) { if (index == 0) { head = head.next; } else { Node preNode = GetByIndex(index - 1); if (preNode.next == null) { throw new ArgumentOutOfRangeException("index", "索引超出范围"); } preNode.next = preNode.next.next; } count--; } public override string ToString() { string s = ""; for (Node tem = head; tem != null;tem=tem.next ) { s += tem.ToString()+" "; } return s; } private Node GetByIndex(int index) { if (index < 0 || index >= this.count) { throw new ArgumentOutOfRangeException("index", "索引超出范围"); } Node tempNode = this.head; for (int i = 0; i < index; i++) { tempNode = tempNode.next; } return tempNode; } }