using
System;
using
System.Collections.Generic;
using
System.Runtime.CompilerServices;
public
class
Node {
public
int
value;
public
int
npx;
public
Node(
int
value)
{
this
.value = value;
this
.npx = 0;
}
}
public
class
XorLinkedList {
Node head;
List<Node> nodes;
public
XorLinkedList()
{
this
.head =
null
;
this
.nodes =
new
List<Node>();
}
public
void
Insert(
int
value)
{
Node node =
new
Node(value);
if
(head ==
null
) {
head = node;
}
else
{
head.npx = RuntimeHelpers.GetHashCode(node)
^ head.npx;
node.npx = RuntimeHelpers.GetHashCode(head);
head = node;
}
nodes.Add(node);
}
public
int
Length()
{
if
(!IsEmpty()) {
int
prevId = 0;
Node node = head;
int
nextId = 1;
int
count = 1;
while
(nextId != 0) {
nextId = prevId ^ node.npx;
if
(nextId != 0) {
prevId
= RuntimeHelpers.GetHashCode(node);
node = GetTypeCastedNode(nextId);
count++;
}
else
{
return
count;
}
}
}
return
0;
}
public
void
PrintMiddle(
int
length)
{
if
(head !=
null
) {
int
prevId = 0;
Node node = head;
int
nextId = 1;
int
middle = length / 2;
int
count = 0;
Node prev =
null
;
while
(count != middle) {
count++;
nextId = prevId ^ node.npx;
if
(nextId != 0) {
prevId
= RuntimeHelpers.GetHashCode(node);
prev = node;
node = GetTypeCastedNode(nextId);
}
else
{
return
;
}
}
if
(length % 2 != 0) {
Console.Write(node.value +
" "
);
}
else
{
Console.Write(prev.value +
" "
+ node.value
+
" "
);
}
}
}
public
bool
IsEmpty() {
return
head ==
null
; }
public
Node GetTypeCastedNode(
int
id)
{
foreach
(Node n
in
nodes)
{
if
(RuntimeHelpers.GetHashCode(n) == id) {
return
n;
}
}
return
null
;
}
}
public
class
GFG {
public
static
void
Main(
string
[] args)
{
XorLinkedList xorLinkedList =
new
XorLinkedList();
xorLinkedList.Insert(4);
xorLinkedList.Insert(7);
xorLinkedList.Insert(5);
int
length = xorLinkedList.Length();
xorLinkedList.PrintMiddle(length);
}
}