using
System;
public
class
LinkedList
{
Node head;
class
Node
{
public
int
data;
public
Node next;
public
Node(
int
d)
{
data = d;
next =
null
;
}
}
void
deleteNode(Node node, Node n)
{
if
(node == n)
{
if
(node.next ==
null
)
{
Console.WriteLine(
"There is only one node. The list "
+
"can't be made empty "
);
return
;
}
node.data = node.next.data;
n = node.next;
node.next = node.next.next;
GC.Collect();
return
;
}
Node prev = node;
while
(prev.next !=
null
&& prev.next != n)
{
prev = prev.next;
}
if
(prev.next ==
null
)
{
Console.WriteLine(
"Given node is not"
+
"present in Linked List"
);
return
;
}
prev.next = prev.next.next;
GC.Collect();
return
;
}
void
printList(Node head)
{
while
(head !=
null
)
{
Console.Write(head.data +
" "
);
head = head.next;
}
Console.WriteLine(
""
);
}
public
static
void
Main(String[] args)
{
LinkedList list =
new
LinkedList();
list.head =
new
Node(12);
list.head.next =
new
Node(15);
list.head.next.next =
new
Node(10);
list.head.next.next.next =
new
Node(11);
list.head.next.next.next.next =
new
Node(5);
list.head.next.next.next.next.next =
new
Node(6);
list.head.next.next.next.next.next.next =
new
Node(2);
list.head.next.next.next.next.next.next.next =
new
Node(3);
Console.WriteLine(
"Given Linked List :"
);
list.printList(list.head);
Console.WriteLine(
""
);
Console.WriteLine(
"Deleting node :"
+
list.head.next.next.data);
list.deleteNode(list.head, list.head.next.next);
Console.WriteLine(
"Modified Linked list :"
);
list.printList(list.head);
Console.WriteLine(
""
);
Console.WriteLine(
"Deleting first Node"
);
list.deleteNode(list.head, list.head);
Console.WriteLine(
"Modified Linked List"
);
list.printList(list.head);
}
}