Reputation: 41
I've made a Link List program in C# which creates a link list of 10 random nodes. But instead I want to manually enter the numbers myself. I'm not sure how to add a function so that I can manually add the numbers myself when the program runs rather than having them random generated? I've tried the code below but it doesn't seem to work. Any help would be appreciated
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;
}
}
}
Upvotes: 0
Views: 251
Reputation: 11364
This will ask you to out in the values manually
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();
}
Upvotes: 1