using
System;
using
System.Collections.Generic;
using
System.Runtime.CompilerServices;
class
Node {
public
int
value;
public
int
npx;
public
Node(
int
value)
{
this
.value = value;
this
.npx = 0;
}
}
class
XorLinkedList {
private
Node head;
private
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 = TypeCast(nextId);
count++;
}
else
{
return
count;
}
}
}
else
{
return
0;
}
return
0;
}
public
void
NthNode(
int
N)
{
int
count = 1;
int
prevId = 0;
int
prev1Id = 0;
Node node = head;
Node node1 = head;
int
nextId = 1;
int
next1Id = 1;
while
(nextId != 0 && count < N) {
nextId = prevId ^ node.npx;
if
(nextId != 0) {
prevId = RuntimeHelpers.GetHashCode(node);
node = TypeCast(nextId);
count++;
}
else
{
Console.WriteLine(
"Wrong Input"
);
return
;
}
}
nextId = prevId ^ node.npx;
prevId = RuntimeHelpers.GetHashCode(node);
node = TypeCast(nextId);
if
(nextId == 0 && count < N) {
Console.WriteLine(
"Wrong Input"
);
return
;
}
while
(nextId != 0) {
nextId = prevId ^ node.npx;
next1Id = prev1Id ^ node1.npx;
if
(nextId != 0) {
prevId = RuntimeHelpers.GetHashCode(node);
node = TypeCast(nextId);
}
if
(nextId != 0) {
prev1Id = RuntimeHelpers.GetHashCode(node1);
node1 = TypeCast(next1Id);
}
}
node1 = TypeCast(next1Id);
Console.WriteLine(node1.value);
}
public
void
PrintList()
{
if
(head !=
null
) {
int
prevId = 0;
Node node = head;
int
nextId = 1;
Console.Write(node.value +
" "
);
while
(nextId != 0) {
nextId = prevId ^ node.npx;
if
(nextId != 0) {
prevId
= RuntimeHelpers.GetHashCode(node);
node = TypeCast(nextId);
Console.Write(node.value +
" "
);
}
else
{
return
;
}
}
}
}
public
bool
IsEmpty() {
return
head ==
null
; }
private
Node TypeCast(
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(0);
xorLinkedList.Insert(2);
xorLinkedList.Insert(1);
xorLinkedList.Insert(3);
xorLinkedList.Insert(11);
xorLinkedList.Insert(8);
xorLinkedList.Insert(6);
xorLinkedList.Insert(7);
xorLinkedList.NthNode(3);
}
}