Answer the question
In order to leave comments, you need to log in
An example of the implementation of a singly linked list in C #, It's not clear where the Netx property of the Head object comes from?
There is the following code, linked list. Everything works correctly, but why?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
internal class Node
{
public int Value { get; set; }
public Node Next { get; set; }
}
internal class LinkList
{
public void Push(int value)
{
Size++;
var node = new Node() {Value = value};
if (Head == null)
{
Head = node;
}
else
{
Current.Next = node;
}
Current = node;
}
public void ListNodes()
{
Node tempNode = Head;
while (tempNode != null)
{
Console.WriteLine(tempNode.Value);
tempNode = tempNode.Next;
}
}
public int this[int position]
{
get
{
Node tempNode = Head;
for (int i = 0; i < position; ++i)
// переходим к следующему узлу списка
tempNode = tempNode.Next;
return tempNode.Value;
}
}
private Node Head { get; set; }
private Node Tails { get; set; }
private Node Current { get; set; }
private Node Current1 { get; set; }
private int Size { get; set; }
}
class Program
{
private static void Main(string[] args)
{
var node = new LinkList();
node.Push(1);
node.Push(2);
node.Push(3);
node.Push(4);
node.Push(9);
node.ListNodes();
Console.ReadKey();
}
}
}
var node = new Node() {Value = value};
if (Head == null)
{
Head = node;
}
else
{
Current.Next = node;
}
Current = node;
Answer the question
In order to leave comments, you need to log in
When the list is empty, Current and Head are null. After the first element is added, Current and Head are the same object, and when the second element is added, the line Current.Next = node; - and at this point Head.Next is set (because Current and Head are the same).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question