如何手动将节点添加到链接列表C#

问题描述

我已经用C#制作了一个链接列表程序,该程序创建了一个包含10个随机节点的链接列表。但是我想自己手动输入数字。我不确定如何添加函数,以便我可以在程序运行时手动添加数字,而不是随机生成这些数字?我已经尝试了下面的代码,但它似乎无法正常工作。任何帮助将不胜感激

namespace Linked_List
{
class Program
{

    public static void Main(String[] args)
    {
        Console.WriteLine("Linked List: ");
        int size = 10;
        int[] a;

        a = new int[size + 1];

        for (int i = 1; i <= size; i++)

        {
            Console.WriteLine("What value do you want to add?");
            a[i] = Convert.ToInt32(Console.ReadLine());
            Node n = new Node(a[i]);


            Node head = List(a,n);
            print_nodes(head); //used to print the values
            Console.ReadLine();
        }

    }
    public class Node
    {
        public int data;
        public Node next;
    };

    static Node add(Node head,int data) //Add nodes
    {
        Node temp = new Node();
        Node current;
        temp.data = data;
        temp.next = null; //next point will be null

        if (head == null) // if head is null
            head = temp;
        else
        {
            current = head;
            while (current.next != null)
                current = current.next;
            current.next = temp; //links to new node
        }
        return head;
    }

    static void print_nodes(Node head) //print the values in list
    {
        while (head != null) //while head is not null
        {
            Console.Write(head.data + " "); //outputs the numbers
            head = head.next;
        }
    }

    static Node List(int[] a,int n)
    {
        Node head = null; //head is originally null
        for (int i = 1; i <= n; i++)
            head = add(head,a[i]);
        return head;
    }

   
}
}

解决方法

这将要求您手动输入值

youtube_player_flutte