如何手动将节点添加到链接列表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;
}

}
}

这将要求您手动输入值

public static void Main(String[] args)
{
Console.WriteLine("Linked List: ");
int n = 10;
Random r = new Random(); 
int[] a;
a = new int[n + 1];
for (int i = 1; i <= n; i++)
a[i] = int.Parse(Console.ReadLine()); // here, no extra class needed
Node head = List(a, n);
print_nodes(head); 
Console.ReadLine();
}

相关内容

  • 没有找到相关文章

最新更新