如何在c#中将链表转换为数组

本文关键字:链表 转换 数组 | 更新日期: 2023-09-27 17:51:18

为了学校的项目,我正在制作一个RPN计算器。这个计算器有一个抽象类Stack,栈的三种不同实现都是从这个抽象类派生出来的。其中之一是链表堆栈。对于这些堆栈,我必须显示堆栈上的值。为此,我使用了一个数组。对于我的数组栈和列表栈来说,这很容易,但我不知道如何将链表转换为数组。最好的方法是什么?

这是我用于链表的代码。

public class Node
{
    public int data;
    public Node next;
    public Node(int i)
    {
        data = i;
        next = null;
    }
    public void Add(int i)
    {
        if (next == null)
        {
            next = new Node(i);
        }
        else
        {
            next.Add(i);
        }
    }        
}
public class MyLinkedList
{
    private Node headNode;
    private int count;
    public MyLinkedList()
    {
        headNode = null;
        count = 0;
    }
    public int Count()
    {
        return count;
    }
    public void Add(int i)
    {
        if (headNode == null)
        {
            headNode = new Node(i);
        }
        else
        {
            headNode.Add(i);
        }
        count++;
    }

如何在c#中将链表转换为数组

  1. 在LinkedList上实现IEnumerable
  2. using System.Linq;
  3. 呼叫LinkedList上的ToArray

实现IEnumerable是微不足道的。只需从列表中的根节点yield return Node.data;开始,然后移动到下一个节点。冲洗并重复,直到下一个节点是null

正如@Will建议的那样,我会通过您的类实现IEnumerable<int>。这将带您进入LINQ的强大世界,在这里您将能够将链表转换为数组,列表或仅过滤节点:

public class MyLinkedList : IEnumerable<int>
{
    // your code here
    public IEnumerator<int> GetEnumerator()
    {
        Node current = headNode;
        while(current != null)
        {
            yield return current.data;
            current = current.next;
        }
    }
    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

现在你可以在你的类中使用所有LINQ扩展:

MyLinkedList myList = new MyLinkedList();
myList.Add(10);
myList.Add(15);
myList.Add(20);
int[] array = myList.ToArray();
List<int> list = myList.ToList();
// items above 13
var items = myList.Where(i => i > 13);

为你的类添加一个新方法

public class MyLinkedList
{
  ... keep existing methods here ...
  public int[] ToArray() {
    var result = new int[count]();
    var index = 0;
    var node = headnode;
    while (node != null) {
      result[index] = node.data;
      node = node.next;
    }
    return result;
  }

呃…类似的东西?

public class MyLinkedList {
  ...
  public Node[] ToArray() {
    // You´ve got pre-computed count - let´s use it
    Node[] result = new Node[count]; 
    Node node = headNode;
    for (int i = 0; i < result.Length; ++i) {  
      result[i] = node;
      node = node.next;
    }
    return result;
  }
}

注:公共字段,如Node类中的next,是一个坏做法。将它们转换为属性