Added indexing methods to linked list

This commit is contained in:
Luke Else 2022-03-04 10:10:55 +00:00
parent 2382011f26
commit dc2768f1ac
3 changed files with 68 additions and 8 deletions

View File

@ -42,9 +42,26 @@ namespace C_.Datastructures
return list; return list;
} }
public T? this[int i]
{
get {
Node<T> node = Traverse(i);
if (node != null) return node.Value;
return default(T);
}
set
{
if (i < Count)
{
Node<T> node = Traverse(i);
node.Value = value;
}
}
}
public void Add(T value){
public void Append(T value){
Node<T> newItem = Node<T>.Create(value, default(Node<T>)); Node<T> newItem = Node<T>.Create(value, default(Node<T>));
Count++; Count++;
@ -96,5 +113,21 @@ namespace C_.Datastructures
} }
return node; return node;
} }
private Node<T>? Traverse(int n)
{
//Start at given point in list
Node<T>? node = Head;
if (node != null)
{
//Continue to end of list
for (int i = 0; i < n; i++)
{
if (node.Next == null) return null;
node = (Node<T>)node.Next;
}
}
return node;
}
} }
} }

View File

@ -6,16 +6,18 @@ Console.WriteLine("Hello, World!");
LinkedList<int> list = new LinkedList<int>(); LinkedList<int> list = new LinkedList<int>();
list.Add(1); list.Append(1);
list.Add(2); list.Append(2);
list.Add(3); list.Append(3);
LinkedList<int> list2 = new LinkedList<int>(); LinkedList<int> list2 = new LinkedList<int>();
list2.Add(1); list2.Append(1);
list2.Add(2); list2.Append(2);
list2.Add(3); list2.Append(3);
LinkedList<int> list3 = LinkedList<int>.Create(list, list); LinkedList<int> list3 = LinkedList<int>.Create(list, list2);
int x = list3[2] = 5;
Console.ReadLine(); Console.ReadLine();

25
C#/c#.sln Normal file
View File

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.1.32210.238
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "C#", "C#.csproj", "{CBD2D14D-2DD3-473C-A11D-23867ACD7056}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{CBD2D14D-2DD3-473C-A11D-23867ACD7056}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CBD2D14D-2DD3-473C-A11D-23867ACD7056}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CBD2D14D-2DD3-473C-A11D-23867ACD7056}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CBD2D14D-2DD3-473C-A11D-23867ACD7056}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {3B808CFA-3B43-4C7E-AD79-0CF0CA3FB904}
EndGlobalSection
EndGlobal