using System;
namespace ConsoleApplication1
{
public class Node
{
public Node Next;
public object Data;
}
public class LinkedList
{
private Node head;
private Node current;
public int Count;
public LinkedList()
{
head = new Node();
current = head;
}
public void AddToLast(object data)
{
Node newNode = new Node();
newNode.Data = data;
current.Next = newNode;
current = newNode;
Count++;
}
public void AddToStart(object _data)
{
Node newNode = new Node() { Data = _data };
newNode.Next = head.Next;
head.Next = newNode;
Count++;
}
public void RemoveFromStart()
{
if (Count > 0)
{
head.Next = head.Next.Next;
Count--;
}
}
public void RemoveFromLast()
{
Node curr = head, before_last = null;
if (head == null) return;
if (head.Next == null)
{
head = null;
return;
}
while (curr.Next != null)
{
before_last = curr;
curr = curr.Next;
}
before_last.Next = null;
Count--;
}
public void PrintAllNodes()
{
Node curr = head;
Console.Write("Head->");
while (curr.Next != null)
{
curr = curr.Next;
Console.Write(curr.Data);
Console.Write("->");
}
Console.WriteLine("NULL");
}
static void Main(string[] args)
{
LinkedList llist = new LinkedList();
llist.PrintAllNodes();
llist.AddToLast("c#");
llist.PrintAllNodes();
llist.AddToLast("Java");
llist.AddToLast(100);
llist.PrintAllNodes();
llist.AddToLast("JavaScript");
llist.AddToLast(300);
llist.AddToLast("C++");
llist.PrintAllNodes();
Console.WriteLine("Total Nodes: {0}\n", llist.Count);
llist.RemoveFromLast();
llist.RemoveFromLast();
llist.PrintAllNodes();
Console.WriteLine("Total Nodes: {0}", llist.Count);
}
}
}
/*
run:
Head->NULL
Head->c#->NULL
Head->c#->Java->100->NULL
Head->c#->Java->100->JavaScript->300->C++->NULL
Total Nodes: 6
Head->c#->Java->100->JavaScript->NULL
Total Nodes: 4
*/