我正在学习如何在c#中创建链表。我有下面的代码不适合我。我只是想在下面添加主节点,然后迭代将打印到控制台的所有节点。如何在链表中创建多个节点,然后遍历节点
using System;
class node
{
public object data;
public node next;
public node()
{
data = null;
next = null;
}
public node(object o)
{
data = o;
next = null;
}
public node(object data, node next)
{
this.data = data;
this.next = next;
}
}
class linkedList
{
private node headNode;
private node tailNode;
int node_count;
public void add(object entry)
{
if (headNode == null)
{
node newNode = new node(entry);
headNode = newNode;
++node_count;
}
else
{
if (node_count == 1)
{
node newNode = new node(entry, headNode);
tailNode = newNode;
}
else
{
node newNode = new node(entry, tailNode);
tailNode = newNode;
}
++node_count;
}
}
public void returnData()
{
if (headNode.next != null)
{
while (headNode.next != null)
{
Console.WriteLine(headNode.data + "\n");
}
}
else
Console.WriteLine("Not Available");
}
}
class Exercise
{
static int Main()
{
linkedList ll = new linkedList();
ll.add(8);
ll.add(2);
ll.add(7);
ll.add(4);
ll.add(9);
ll.add(10);
ll.returnData();
Console.ReadLine();
return 0;
}
}
如何它不起作用吗? – BoltClock
@boltclock当我编译并运行它时出现了不可用 –
建议使您的代码更易于阅读本身和其他人 - 开始遵循.NET命名约定:http://msdn.microsoft.com/zh-cn/ us/library/ms229045.aspx然后更具体地说错误比“它不可用”。阅读我的指南,问好问题:http://tinyurl.com/so-hints –