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();
}
}
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.根据单链表的功能,(新增元素是插入到后面还是前面),根据需要声明两个变量,当前节点变量和头结点变量