Here is the code:
class Program
{
static void Main(string[] args)
{
// This Solution is written by me and is not completely tested. Please comment if you found any alternative solutions or any enhancement to my solution.
LinkedList l = new LinkedList();
l.add(1);
l.add(2);
l.add(3);
l.add(4);
l.add(5);
l.add(6);
l.Display();
l.RemoveMiddle();
l.Display();
l.RemoveMiddle();
l.Display();
}
}
public class LinkedList
{
public node head { get; set; }
public int lenght { get; set; }
public void add(int data)
{
node n = new node(data);
lenght++;
if (head == null)
{
head = n;
}
else
{
var temp = head;
while (temp.next != null)
{
temp = temp.next;
}
temp.next = n;
}
}
public void Display()
{
var temp = head;
Console.WriteLine("------------");
while (temp != null)
{
Console.WriteLine(temp.data);
temp = temp.next;
}
Console.WriteLine("------------");
}
public void RemoveMiddle()
{
int mid = lenght / 2;
var temp = head;
int count = 0;
while (temp.next != null)
{
count++;
if (count == mid)
{
temp.next = temp.next.next;
lenght--;
return;
}
temp = temp.next;
}
}
}
public class node
{
public int data { get; set; }
public node next { get; set; }
public node(int _data)
{
data = _data;
}
}
Output:
------------
1
2
3
4
5
6
------------
------------
1
2
3
5
6
------------
------------
1
2
5
6
------------
Press any key to continue . . .
Popular Posts
-
Here is the code: // => Brute Force Solution: O(m* n) static long arrayManipulation(int n, int[][] queries) { ...
-
Whatever it is one fine day everyone on this planet who are born have to die for sure. When you are close ones are with you, you wont know ...
-
HTML: <div class="outer-container"> <div class="inner-container"> <div class="t...
No comments:
Post a Comment