I'm working on a radix sort algorithm with linked list. I have in mind how I'm going to solve it, but I need to be able to delete the whole linked list (deleting node one by one when looping through linked list). The problem which I encountered is my current (node) pointer doesn't get the value first. I have tried many different things, but I guess I don't grasp how to reset the pointers 'first', 'current', 'left', 'right' when deleting a node
Radixsort.cs:
public static void Counting_sort(LinkedList<int> list, int exp)
{
LinkedList<int> D = new LinkedList<int>();
LinkedList<int>[] lists = new LinkedList<int>[10];
for (int i = 0; i < lists.Length; i++)
{
lists[i] = new LinkedList<int>();
}
// Skaiciu daznumas
int number = 0;
for (list.Beginning(); list.Exists(); list.Next())
{
number = (list.Take() / exp % 10);
lists[number].Add(list.Take());
list.Remove(list.TakeNode()); <---------- Removing node one by one till it's empty
}
for (int i = 0; i < lists.Length; i++)
{
for (list.Beginning(); list.Exists(); list.Next())
{
//list.Add(lists)
}
}
}
public static void Radix_sort(LinkedList<NumberPlate> list)
{
LinkedList<int> intList = new LinkedList<int>();
AddIntToLinkedList(list, intList);
for (int exp = 1; exp < Math.Pow(10, 9); exp *= 10)
{
Counting_sort(intList, exp);
}
}
LinkedList.cs
public class LinkedList<T> : IEnumerable<T> where T : IComparable<T>, IEquatable<T>
{
public sealed class Node<T>
{
public Node<T> Right;
public Node<T> Left;
public T data;
public Node(T value, Node<T> left, Node<T> right)
{
Left = left;
Right = right;
data = value;
}
}
private Node<T> first;
private Node<T> last;
private Node<T> current;
public int size;
public LinkedList()
{
first = null;
last = null;
current = null;
size = 0;
}
public void Add(T element)
{
var node = new Node<T>(element, last, null);
if (first != null)
{
last.Right = node;
last = node;
}
else
{
first = node;
last = node;
}
current = node;
size++;
}
public void Remove(Node<T> node)
{
if (node == first)
{
first = first.Right;
}
else if (node == last)
{
last = last.Left;
}
else if (node.Left != null)
{
node.Left.Right = node.Right;
}
else if (node.Right != null)
{
node.Right.Left = node.Left;
}
size--;
}
public void Beginning()
{
current = first;
}
public void End()
{
current = last;
}
public void Next()
{
current = current.Right;
}
public void Previous()
{
current = current.Left;
}
public bool Exists()
{
return current != null;
}
public T Take()
{
return current.data;
}
public Node<T> TakeNode()
{
return current;
}
I think you should be able to do this to clear a list:
foreach (var node in list)
{
list.Remove(node);
}
The Remove method is already implemented for you on the LinkedList class, so you should make use of it.
Because the LinkedList implements IEnumerable, you can iterate over it using foreach.