Skip to content

Instantly share code, notes, and snippets.

@ganeshran
Created January 13, 2017 16:44
Show Gist options
  • Save ganeshran/88df7c76cb40f0801d14323860b523e1 to your computer and use it in GitHub Desktop.
Save ganeshran/88df7c76cb40f0801d14323860b523e1 to your computer and use it in GitHub Desktop.
LinkedListOperations
using System;
using System.Reflection.Emit;
using System.Text;
using System.Threading;
namespace AlgoPractise
{
public class Node
{
public int Data { get; set; }
public Node Next { get; set; }
public Node(int data)
{
this.Data = data;
}
}
public class DummyDataSource
{
public static Node GetLinkedList()
{
var root = new Node(5);
var temp = root;
for (int i = 0; i < 10; i++)
{
temp.Next = new Node(new Random().Next(0,100));
Thread.Sleep(50);
temp = temp.Next;
}
return root;
}
}
class LinkedListCode
{
public Node TestList { get; set; }
public LinkedListCode()
{
this.TestList = DummyDataSource.GetLinkedList();
}
public void CheckDummyData()
{
var list = DummyDataSource.GetLinkedList();
}
public void PrintListLength()
{
int count = 0;
var temp = this.TestList;
while (temp != null)
{
count++;
temp = temp.Next;
}
Console.WriteLine(count);
}
public void PrintListElements()
{
var temp = this.TestList;
while (temp != null)
{
Console.Write(temp.Next == null ? "{0}\n" : "{0} -> ", temp.Data);
temp = temp.Next;
}
}
public void InsertAtBeginning(int newitemData)
{
var newNode = new Node(newitemData) {Next = this.TestList};
this.TestList = newNode;
}
public void InsertAtEnd(int newItemData)
{
var newNode = new Node(newItemData);
var temp = this.TestList;
while (temp.Next != null)
{
temp = temp.Next;
}
temp.Next = newNode;
}
public void InsertAtPosition(int newItemData, int position)
{
var newNode = new Node(newItemData);
var temp = this.TestList;
for (int i = 1; i < position; i++)
{
if (temp.Next == null || temp.Next.Next == null)
{
Console.WriteLine("Not enough elements to perform insertion");
return;
}
temp = temp.Next;
}
newNode.Next = temp.Next;
temp.Next = newNode;
}
public void DeleteAtPosition(int position)
{
var temp = this.TestList;
Node prev = null;
int count = 1;
if (this.TestList == null)
{
Console.WriteLine("List is Empty, returning");
return;
}
if (position == 1)
{
this.TestList = this.TestList.Next;
}
else
{
while (temp != null && count < position)
{
prev = temp;
temp = temp.Next;
count++;
}
if (prev == null)
{
Console.WriteLine("Position is not found. exiting");
}
else
{
prev.Next = temp.Next;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment