- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Collections;
- namespace 泛型
- {
- //简单链表的实现,单向(泛型)
- class 泛型类
- {
- public static void Main()
- {
- LinkedList<string> list = new LinkedList<string>();
- list.AddLast("500");
- list.AddLast("400");
- list.AddLast("300");
- list.AddLast("200");
- //使用泛型版的IEnumerable时,foreach也是类型安全的,些时不可能写 string之外的类型
- foreach (string i in list)
- {
- Console.WriteLine(i);
- }
- Console.ReadLine();
- }
- }
- ////泛型类的定义与一般类相似,只要使用泛型类型声明,之后,这个类型就可以做为一个字段成员,或者参数类型。
- class LinkedListNode<T>
- {
- //项目值
- private T value;
- private LinkedListNode<T> next;
- private LinkedListNode<T> prev;
- public LinkedListNode(T value)
- {
- this.value = value;
- }
- public T Value
- {
- //只读属性
- get
- {
- return this.value;
- }
- }
- //下一个
- public LinkedListNode<T> Next
- {
- get { return next; }
- set { next = value; }
- }
- //上一个
- public LinkedListNode<T> Prev
- {
- get { return prev; }
- set { prev = value; }
- }
- }
- class LinkedList<T> : IEnumerable<T>
- {
- //第一个
- private LinkedListNode<T> first;
- internal LinkedListNode<T> First
- {
- get { return first; }
- set { first = value; }
- }
- //最后一个
- private LinkedListNode<T> last;
- internal LinkedListNode<T> Last
- {
- get { return last; }
- set { last = value; }
- }
- //从后面插入
- public LinkedListNode<T> AddLast(T node)
- {
- LinkedListNode<T> newNode = new LinkedListNode<T>(node);
- if (first == null)
- {
- //Last的引用一直要更新
- first = newNode;
- last = first;
- }
- else
- {
- //把当前最后一个节点的下一个节点的引用 指向新对象
- last.Next = newNode;
- //更新最后一个节点
- last = newNode;
- }
- return newNode;
- }
- public IEnumerator<T> GetEnumerator()
- {
- LinkedListNode<T> current = first;
- while (current != null)
- {
- yield return current.Value;
- //新引用指向下一个节点的地址
- current = current.Next;
- }
- }
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
- }
- }
C#中的泛型链表的实现
最新推荐文章于 2025-05-17 11:56:38 发布