C#自定义链表

来源:互联网 发布:手机网络兼职 编辑:程序博客网 时间:2024/05/21 09:16

C#中的链表结构在程序中十分常见,用处很广。
链表结构中,每个节点由值部分和指针部分组成,值部分即存储的数据,指针指向下一个节点,从而使得每个节点能够连接起来,值和指针就像骨骼和关节一样。

一、节点结构

自定义链表,首先定义出节点的结构,用类表示为:

public Class Node<T>{      //不确定value的值类型所以用泛型public T value;            //值public Node<T> point;      //指针}

二、自定义List链表

定义完节点,下面开始构造List链表结构。自定义链表中属性有:元素个数、索引器,方法有添加、插入、遍历。其中遍历方法需要实现IEnumerable接口。

思路

改变链表中节点的指向。

1.添加方法Add(T value)

(1)定义全局变量first和last表示链表中的根节点和最后一个节点;
(2)判断last是否为空,为空证明链表中没有元素,将需要插入的value值赋予给first,然后让last指向first;
(3)当last不为空时,新建节点node并赋予value值,用来表示插入的节点。将当前最后一个节点last指针指向node,然后node节点即成为最后一个节点
(4)元素个数+1

2.插入方法Insert(T value,int index)

(1)新建要插入的节点node并赋予value值;
(2)如果index=0,则需要更换根节点,让node指向first,然后重新赋予first的值为node;
(3)如果index>0,则先找出index-1位置的节点temp,让node指向原来index位置的节点(temp.point),然后让temp指向node节点,这样node便成为了index处的节点。
(4)元素个数+1

MyList类代码

public Class MyList<T>:IEnumerable{    //表示根节点    public Node<T> first = new Node<T>();    //表示最后一个节点    public Node<T> last = new Node<T>();    //节点个数    private int count ;    //属性          public int Count{               get{        return count;        }    }    //索引器,根据节点一一连接的特点,利用While循环找出第index个节点    public T this[int index]{        get{            Node<T> node = first;            int i = 0;            while(i!=index)            {                i++;                node = node.point;            }             return node.value;        }    }    //添加方法    public void Add(T value){        //最后一个节点为空,证明first节点未添加元素        if(temp == null)         {            //将value值赋予根节点            first.value = value;            last = first;        }        //最后一个节点不为空        else{            //新建一个节点            Node<T> node = new Node<T>();            //赋予value值            node.value = value;            //将最后一个节点指向当前新建的节点            last.point = node;            //新建的节点变为最后一个节点            last = node;        }    }    //插入方法    public void Insert(T value ,int index)    {                   //新建需要插入的节点并赋予value值        Node<T> newNode = new Node<T>();        new Node.value = value;        //如果插入到0的位置,需要更换根节点        if(index == 0){            //首先将新的节点指向根节点            newNode.point = first;            //更换根节点            first = newNode;        }        //如果插入非0的位置        else{            Node<T> node = first;            int i = 0;            //找出插入点的前一个节点            while(i!=index){                i++;                node = node.point;            }            //将节点插入            newNode.point = node.point;            node.point = newNode;        }        count++;    }    //foreach遍历,需要实现IEnumerable接口    public IEnumerator GetEnumerator(){        Node node = first;        while(node != null){            yield return node.value;            node = node.point;        }    }}
0 0
原创粉丝点击