using System;
using System.Collections;
using System.Collections.Generic;
class GFG
{
public class Node
{
public int data;
public Node next, random;
public Node(int data)
{
this.data = data;
this.next = this.random = null;
}
}
public class LinkedList
{
public Node head;
public LinkedList(Node head)
{
this.head = head;
}
public void push(int data)
{
Node node = new Node(data);
node.next = this.head;
this.head = node;
}
public void print()
{
Node temp = head;
while (temp != null)
{
Node random = temp.random;
int randomData = (random != null)? random.data: -1;
Console.WriteLine("Data = " + temp.data +
", Random data = "+ randomData);
temp = temp.next;
}
}
public LinkedList clone()
{
Node origCurr = this.head, cloneCurr = null;
Dictionary<Node, Node> map = new Dictionary<Node, Node>();
while (origCurr != null)
{
cloneCurr = new Node(origCurr.data);
map.Add(origCurr, cloneCurr);
origCurr = origCurr.next;
}
origCurr = this.head;
while (origCurr != null)
{
cloneCurr = map[origCurr];
if(origCurr.next != null)
cloneCurr.next = map[origCurr.next];
if(origCurr.random != null)
cloneCurr.random = map[origCurr.random];
origCurr = origCurr.next;
}
return new LinkedList(map[this.head]);
}
}
public static void Main(String []args)
{
LinkedList list = new LinkedList(new Node(5));
list.push(4);
list.push(3);
list.push(2);
list.push(1);
list.head.random = list.head.next.next;
list.head.next.random =
list.head.next.next.next;
list.head.next.next.random =
list.head.next.next.next.next;
list.head.next.next.next.random =
list.head.next.next.next.next.next;
list.head.next.next.next.next.random =
list.head.next;
LinkedList clone = list.clone();
Console.WriteLine("Original linked list");
list.print();
Console.WriteLine("\nCloned linked list");
clone.print();
}
}