using
System;
class
GFG{
class
Node
{
public
int
data;
public
Node left;
public
Node right;
public
Node up;
public
Node down;
};
static
Node createNode(
int
value)
{
Node temp =
new
Node();
temp.data = value;
temp.left =
null
;
temp.right =
null
;
temp.up =
null
;
temp.down =
null
;
return
temp;
}
static
Node createListWithRightPointer(
int
k,
int
i)
{
if
(i > k)
return
null
;
Node node = createNode(i);
node.right = createListWithRightPointer(k,
i + 1);
return
node;
}
static
Node createKsinglyList(
int
k)
{
int
rNum = 1;
int
limit = k;
Node head =
null
;
Node rowPointer =
null
;
for
(
int
i = 1; i <= k; i++)
{
Node templist =createListWithRightPointer(limit,
rNum);
if
(head ==
null
)
{
head = templist;
rowPointer = head;
}
else
{
rowPointer.down = templist;
rowPointer = rowPointer.down;
}
rNum = rNum + k;
limit = limit + k;
}
return
head;
}
static
void
mergeKListWithDownPointer(Node head)
{
Node first =
null
;
Node second =
null
;
Node start = head;
first = start;
second = first.down;
while
(second !=
null
)
{
while
(first !=
null
|| second !=
null
)
{
first.down = second;
first = first.right;
second = second.right;
}
first = start.down;
second = first.down;
start = start.down;
}
}
static
void
createLoopForEachColumn(Node head)
{
Node first =
null
;
Node last =
null
;
first = head;
last = first;
while
(last.down !=
null
)
{
last = last.down;
}
while
(first !=
null
|| last !=
null
)
{
last.down = first;
first = first.right;
last = last.right;
}
}
static
void
createLoopForEachRow(Node head)
{
Node first =
null
;
Node last =
null
;
Node start =
null
;
start = head;
first = head;
last = first;
while
(last.right !=
null
)
{
last = last.right;
}
while
(first.down != start)
{
last.right = first;
first = first.down;
last = last.down;
}
last.right = first;
}
static
void
display(Node head)
{
Node rPtr;
Node dPtr = head;
Node start = head;
while
(dPtr.down != start)
{
rPtr = dPtr;
while
(rPtr.right != dPtr)
{
Console.Write(rPtr.data +
" "
);
rPtr = rPtr.right;
}
Console.Write(rPtr.data +
" "
);
Console.Write(
"\n"
);
dPtr = dPtr.down;
}
rPtr = dPtr;
while
(rPtr.right != dPtr)
{
Console.Write(rPtr.data +
" "
);
rPtr = rPtr.right;
}
Console.Write(rPtr.data +
" "
);
Console.Write(
"\n"
);
}
static
void
createLoopInList(
int
k)
{
Node head = createKsinglyList(k);
mergeKListWithDownPointer(head);
createLoopForEachColoumn(head);
createLoopForEachRow(head);
display(head);
}
public
static
void
Main(String[] args)
{
int
K = 4;
createLoopInList(K);
}
}