【发布时间】:2020-08-15 21:23:19
【问题描述】:
我用 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;
}
}
}
【问题讨论】:
-
如果您编写了此代码,您应该知道生成随机数的原因。知道这一点,到目前为止,您尝试过做什么?任务是什么?
-
是的,我知道是什么产生了随机数,但如果我摆脱了 Random 函数,我无法弄清楚如何手动添加数字
-
数字应该从哪里来?
-
我想手动输入。我的意思是,我不想使用随机生成器,而是想自己实际输入它们,但不知道该怎么做
-
程序何时运行或只是硬编码?
标签: c# linked-list singly-linked-list