单链表

using UnityEngine;
using System.Collections;

/**
 * 单链表
 **/

public class ListStruct : MonoBehaviour
{
    private class Node
    {
        public object data;
        public Node next = null;


        public Node(object data)
        {
            this.data = data;
        }
    }


    private Node m_Head = null;
    private Node m_Cur = null;


    public void Add(object obj)
    {
        Node node = new Node(obj);
        if (m_Head == null)
        {
            //Debug.Log("XXXXX");
            m_Head = node;
            m_Cur = m_Head;
        }
        else
        {
            //Debug.Log("=====");
            m_Cur.next = node;
            m_Cur = node;
        }
    }


    public bool Remove(object obj)
    {
        if (m_Cur == null)
        {
            return false;
        }
        else
        {
            Node cur = m_Head;
            while (cur.next != null)
            {
                if (cur.next.data.Equals(obj))
                {
                    cur.next = cur.next.next;
                    return true;
                }
                cur = cur.next;
            }
            return false;
        }
    }


    public void Display()
    {
        if (m_Head == null)
        {
            Debug.Log("Empty List");
        }
        else
        {
            Node cur = m_Head;
            while (cur != null)
            {
                Debug.Log("-->" + cur.data.ToString());
                cur = cur.next;
            }
        }
    }


    void Start()
    {
        ListStruct list = new ListStruct();
        list.Display();


        list.Add(1);
        list.Add(2);
        list.Add(3);
        list.Display();
    }
}


总结:

本例子是放在C#脚本中,然后挂在Unity摄像机上运行的。

核心点:1.理解链表结构的原理,然后构造节点类

2.根据单链表的功能,(新增元素是插入到后面还是前面),根据需要声明两个变量,当前节点变量和头结点变量


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值