单链表
来源:互联网 发布:笨办法学python mobi 编辑:程序博客网 时间:2024/05/16 06:36
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.根据单链表的功能,(新增元素是插入到后面还是前面),根据需要声明两个变量,当前节点变量和头结点变量
0 0
- 单链表
- 单链表
- 单链表
- 单链表
- 单链表
- 单链表
- 单链表
- 单链表
- 单链表
- 单链表
- 单链表
- 单链表
- 单链表
- 单链表
- 单链表
- 单链表
- 单链表
- 单链表
- 【C++】继承(虚基类)
- 【C++】多态性(函数重载与虚函数)
- [LeetCode]Edit Distance
- 《失控》读后感
- 数组中累加和为k的最长子数组长度(算法)
- 单链表
- Android实战简易教程-第五十枪(工具类的测试)
- hdu 5406 CRB and Apple
- HDU——2016 decimal system
- TQ2440 学习笔记—— 14、GPIO 接口【实验:用C语言实现】
- 方法的三个关键参数
- Java使用InetAddress类获取主机名和IP地址
- poj 1256 Pick定理
- Android屏幕适配