【发布时间】:2011-09-08 10:12:30
【问题描述】:
我正在学习如何在 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 在我编译和运行时出现不可用
-
建议让您的代码更易于自己和他人阅读 - 开始遵循 .NET 命名约定:msdn.microsoft.com/en-us/library/ms229045.aspx 然后更具体地处理错误,而不是“出现不可用”。阅读我的提问指南:tinyurl.com/so-hints
标签: c# data-structures linked-list