Pro*_*eck 2 visual-studio c#-4.0
我正在研究一个单链表。在创建自己的链表时,我对在自定义链表中打印节点集合感到困惑。
我想知道,单向链表是否像堆栈一样以 LIFO 方式显示其集合?
下面是我自己的 LinkedList AND 节点是一个类,谁能告诉我 Singular LinkedList 是否以 Lifo 方式打印集合。
class MYlinklist
{
Node header;
public void Add(int a)
{
Node n = new Node();
n.element = a;
n.Next = header;
header = n;
}
public void Print()
{
Node n = new Node();
n = header;
while (n != null)
{
Console.WriteLine(n.element.ToString());
n = n.Next;
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果您指的是LinkedList<T>,答案取决于您添加新成员的方式。
如果你想让链表在 LIFO 中迭代,你可以通过始终使用AddFirst添加和RemoveFirst删除来实现。这将导致它的行为非常像一个堆栈。
LinkedList<T>然而,关于 的好处是您可以将列表内的任何位置添加为 O(1) 操作。
编辑:
如果您希望这是 FIFO,则需要更改添加节点的方式,并将它们添加到列表的末尾,而不是开头:
class MyLinkedList
{
Node header;
Node last;
public void Add(int a)
{
Node n = new Node();
n.element = a;
n.Next = null; // We'll put this at the end...
if (last == null)
{
header = n;
last = n;
}
else
{
last.Next = n;
last = n;
}
}
public void Print()
{
Node n = new Node();
n = header;
while (n != null)
{
Console.WriteLine(n.element.ToString());
n = n.Next;
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5435 次 |
| 最近记录: |