public class Node
{
public int item;
public Node next;
public Node(int it)
{
item = it;
next = null;
Console.Write("[{0}]-->", item);
}
}
public class LinkedList
{
public Node top;
public LinkedList(int item)
{
Node n = new Node(item);
top = n;
}
public void Push(int item)
{
Node _node = new Node(item);
//Add Node at before top
if (top == null)
{
top = _node;
}
else
{
_node.next = top;
top = _node;
}
}
public void InsertAfter(Node node, int item)//Inserting item (new node) after given node.
{
Node newNode = new Node(item);
if (top == null) return;
Node nxtNode = top;
while (nxtNode != null)
{
if (nxtNode.item == node.item)
{
newNode.next = nxtNode.next;
nxtNode.next = newNode;
break;
}
else
{
nxtNode = nxtNode.next;
}
}
}
public void Print()
{
if (top == null)
{
Console.WriteLine("List is empty");
return;
}
Node nexNode =top;
while (nexNode != null)
{
Console.WriteLine(nexNode.item);
nexNode = nexNode.next;
}
}
}
class TestLinked
{
public static void Main()
{
LinkedList ll = new LinkedList(1);
Console.WriteLine("Top item=" + ll.top.item); //each newly added item will be top of linked list.
ll.Push(3);
Console.WriteLine("Top item=" + ll.top.item);
ll.Push(5);
Console.WriteLine("Top item=" + ll.top.item);
ll.Push(6);
Console.WriteLine("Top item=" + ll.top.item);
ll.InsertAfter(new Node(3), 4);
ll.Print();
Console.ReadLine();
}
}
{
public int item;
public Node next;
public Node(int it)
{
item = it;
next = null;
Console.Write("[{0}]-->", item);
}
}
public class LinkedList
{
public Node top;
public LinkedList(int item)
{
Node n = new Node(item);
top = n;
}
public void Push(int item)
{
Node _node = new Node(item);
//Add Node at before top
if (top == null)
{
top = _node;
}
else
{
_node.next = top;
top = _node;
}
}
public void InsertAfter(Node node, int item)//Inserting item (new node) after given node.
{
Node newNode = new Node(item);
if (top == null) return;
Node nxtNode = top;
while (nxtNode != null)
{
if (nxtNode.item == node.item)
{
newNode.next = nxtNode.next;
nxtNode.next = newNode;
break;
}
else
{
nxtNode = nxtNode.next;
}
}
}
public void Print()
{
if (top == null)
{
Console.WriteLine("List is empty");
return;
}
Node nexNode =top;
while (nexNode != null)
{
Console.WriteLine(nexNode.item);
nexNode = nexNode.next;
}
}
}
class TestLinked
{
public static void Main()
{
LinkedList ll = new LinkedList(1);
Console.WriteLine("Top item=" + ll.top.item); //each newly added item will be top of linked list.
ll.Push(3);
Console.WriteLine("Top item=" + ll.top.item);
ll.Push(5);
Console.WriteLine("Top item=" + ll.top.item);
ll.Push(6);
Console.WriteLine("Top item=" + ll.top.item);
ll.InsertAfter(new Node(3), 4);
ll.Print();
Console.ReadLine();
}
}
No comments:
Post a Comment