Skip to content

Instantly share code, notes, and snippets.

@srsandy
Created August 4, 2021 20:56
Show Gist options
  • Save srsandy/5e33f0fe146df372e17238e8e12cba62 to your computer and use it in GitHub Desktop.
Save srsandy/5e33f0fe146df372e17238e8e12cba62 to your computer and use it in GitHub Desktop.
C# generic linked list implementation. Contains add, remove and sort (bubble sort).
using System;
using System.Collections.Generic;
using System.Text;
namespace CSharpWork
{
public class MyLinkedList<T> where T: IComparable
{
class Node<G>
{
public Node<G> next;
public G Data;
public Node(G data)
{
Data = data;
next = null;
}
}
private Node<T> head;
private Node<T> tail;
public T First => head.Data;
public T Last => tail.Data;
public MyLinkedList()
{
head = tail = null;
}
public void Add(T data)
{
Node<T> node = new Node<T>(data);
if (head == null)
{
head = node;
tail = node;
}
else
{
tail.next = node;
tail = node;
}
Console.WriteLine("Node added");
}
public void Remove()
{
if (head == null)
{
Console.WriteLine("List empty");
return;
}
if (head.next == null)
{
head = null;
tail = null;
Console.WriteLine("Element remove");
return;
}
Node<T> cursor = head;
while (cursor.next.next != null)
{
cursor = cursor.next;
}
cursor.next = null;
tail = cursor;
Console.WriteLine("Element remove");
}
public void Sort()
{
if (head == null || head.next == null) return;
bool isSorting = true;
while (isSorting)
{
isSorting = false;
Node<T> cursorI = head;
Node<T> prev = null;
while (cursorI != null)
{
Node<T> temp = null;
Node<T> temp2 = null;
if (cursorI.next != null)
{
int cmp = (cursorI.Data as IComparable).CompareTo(cursorI.next.Data);
if (cmp == 1)
{
isSorting = true;
temp = cursorI;
temp2 = cursorI.next;
cursorI.next = temp2.next;
temp2.next = temp;
if (prev != null)
{
prev.next = temp2;
}
// reset head
if (prev == null)
{
head = temp2;
}
prev = temp2;
} else
{
prev = cursorI;
cursorI = cursorI.next;
}
}
else
{
// rest tail
tail = cursorI;
break;
}
}
}
}
public override string ToString()
{
if (head == null)
{
return "List Empty";
}
string list = "";
Node<T> cursor = head;
while (cursor.next != null)
{
list += $"{cursor.Data} -> ";
cursor = cursor.next;
}
list += $"{cursor.Data}";
return list;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment