[我正在研究C#中的列表,我非常怀疑,您在这里看到,属性“ Siguiente”是同一类的类型,我不了解这在内部如何影响代码以及实际上意味着什么,列表有效,该属性用于在列表中创建指针。我的疑虑是
添加其余的代码,我主要关心的是“ CNodo”对象。
欢呼声
using System;
using System.Collections.Generic;
using System.Text;
namespace Lista_Ligada
{
class CNodo
{
private int vDato;
private CNodo vSiguiente = null;
public int Dato1
{
get => vDato;
set => vDato = value ;
}
internal CNodo Siguiente
{
get => vSiguiente;
set => vSiguiente = value;
}
public override string ToString()
{
return string.Format("[{0}]", vDato);
}
public void TextoPrueba()
{
Console.WriteLine("Prueba");
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace Lista_Ligada
{
class CListaLigada
{
private CNodo Ancla;
private CNodo Trabajo ;
private CNodo Trabajo2;
public CListaLigada()
{
Ancla = new CNodo();
Ancla.Siguiente = null;
}
public void Transversa()
{
Trabajo = Ancla;
Console.WriteLine("El ancla tiene un valor de Siguiente de {0}", Trabajo.Siguiente);
Console.WriteLine("El ancla tiene un valor de Dato de {0}", Trabajo.Dato1);
while (Trabajo.Siguiente != null)
{
Trabajo = Trabajo.Siguiente ;
int D = Trabajo.Dato1 ;
Console.WriteLine("{0}", D) ;
Console.WriteLine("{0}", Trabajo.Siguiente);
}
Console.WriteLine();
}
public void Adicionar(int pDato)
{
Trabajo = Ancla;
while (Trabajo.Siguiente != null)
{
Trabajo = Trabajo.Siguiente;
}
CNodo Temp = new CNodo(); // ?
Temp.Dato1 = pDato;
Temp.Siguiente = null;
Trabajo.Siguiente = Temp;
}
}
}
using System;
namespace Lista_Ligada
{
class Program
{
static void Main(string[] args)
{
CListaLigada MiLista = new CListaLigada();
CNodo Txt = new CNodo();
MiLista.Adicionar(19);
MiLista.Adicionar(3);
MiLista.Adicionar(5);
MiLista.Adicionar(7);
MiLista.Adicionar(7);
MiLista.Adicionar(5);
MiLista.Adicionar(3);
MiLista.Adicionar(1);
MiLista.Adicionar(0);
MiLista.Transversa();
Txt.TextoPrueba();
MiLista.Transversa();
}
}
}
类不是对象的实例-类描述对象的行为方式以及它将存储什么数据。如果有一个类,则这样声明:
class MyClass
{
MyClass nextNode;
}
这意味着该类的实例将在其内部保存对相同类的对象的引用。要创建类的实例,请使用关键字new
调用构造函数,例如:
MyClass instance = new MyClass()
现在您的内存中有一个类的实例,并且instance
是对该类的引用。您必须了解,nextNode
中的instance
不是对象-它是对对象的引用。因此可以编写以下几行:
instance.nextNode = instance; //this will assign the same reference to nextNode as instance instance.nextNode = new MyClass(); //this will assign a reference to a different object with the same type MyClass
下面的图像大致描述了引用和对象的存储位置
Internet上有很多很棒的教程,介绍链接列表的工作原理,例如:https://www.tutorialspoint.com/data_structures_algorithms/linked_list_algorithms.htm。因此,现在让我请您介绍其中之一。