linked list c#
using System;
namespace LinkedListPractice
{
public class LinkedList
{
private class Node
{
public int value;
public Node next;
public Node(int value)
{
this.value = value;
}
}
private Node Head;
private Node Tail;
private int size;
public void AddLast(int item)
{
var node = new Node(item);
if (IsEmpty())
Head = Tail = node;
else
{
Tail.next = node;
Tail = node;
}
size++;
}
public void AddFirst(int item)
{
var node = new Node(item);
if (IsEmpty())
Head = Tail = node;
else
{
node.next = Head;
Head = node;
}
size++;
}
private bool IsEmpty()
{
return Head == null;
}
public int IndexOf(int item)
{
int index = 0;
var current = Head;
while (current != null)
{
if (current.value == item) return index;
current = current.next;
index++;
}
return -1;
}
public bool Contains(int item)
{
return IndexOf(item) != -1;
}
public void RemoveFirst()
{
if (IsEmpty())
throw new InvalidOperationException();
if (Head == Tail)
Head = Tail = null;
else
{
var second = Head.next;
Head.next = null;
Head = second;
}
size--;
}
public void RemoveLast()
{
if (IsEmpty())
throw new InvalidOperationException();
if (Head == Tail)
Head = Tail = null;
else
{
var previous = GetPrevious(Tail);
Tail = previous;
Tail.next = null;
}
size--;
}
private Node GetPrevious(Node node)
{
var current = Head;
while (current != null)
{
if (current.next == node) return current;
current = current.next;
}
return null;
}
public int Size()
{
return size;
}
public int[] ToArray()
{
int[] array = new int[size];
var current = Head;
var index = 0;
while (current != null)
{
array[index++] = current.value;
current = current.next;
}
return array;
}
public void Reverse()
{
if (IsEmpty()) return;
var previous = Head;
var current = Head.next;
while (current != null)
{
var next = current.next;
current.next = previous;
previous = current;
current = next;
}
Tail = Head;
Tail.next = null;
Head = previous;
}
public int GetKthFromTheEnd(int k)
{
if (IsEmpty())
throw new InvalidOperationException();
var a = Head;
var b = Head;
for (int i = 0; i < k - 1; i++)
{
b = b.next;
if (b == null)
throw new InvalidOperationException();
}
while (b != Tail)
{
a = a.next;
b = b.next;
}
return a.value;
}
public void PrintMiddle()
{
if (IsEmpty())
throw new InvalidOperationException();
var a = Head;
var b = Head;
while (b != Tail && b.next != Tail)
{
b = b.next.next;
a = a.next;
}
if (b == Tail)
Console.WriteLine(a.value);
else
Console.WriteLine(a.value + ", " + a.next.value);
}
public bool HasLoop()
{
var slow = Head;
var fast = Head;
while (fast != null && fast.next != null)
{
slow = slow.next;
fast = fast.next.next;
if (slow == fast)
return true;
}
return false;
}
}
}