//print regular LinkedList public static void PrintRegularList(Node head){ Node temp = head; while (temp != null) { if (temp.Next != null) Console.Write (temp.Value + "->" + temp.Next.Value); Console.WriteLine (" "); temp = temp.Next; //do not forget this! } }
//Copy regular LinkedList public static Node CopyRegular(Node head){ if (head == null) return null; Node newHead = new Node (head.Value); Node current = head; Node newCurrent = newHead; while (current.Next != null) { Node newNext = new Node (current.Next.Value); newCurrent.Next = newNext; current = current.Next; newCurrent = newCurrent.Next; } return newHead; }
public Node(int value) { this.Value = value; this.Next = null; }
public static void Main (string[] args) { //construct a simple test Linked List ListNode[] testList = new ListNode[]{new ListNode(1),new ListNode(2),new ListNode(3),new ListNode(4)}; for (int i = 0; i < testList.Length-1; i++) { testList [i].Next = testList [i + 1]; } testList [0].Random = testList [2]; testList [1].Random = testList [3]; testList [2].Random = testList [0]; testList [3].Random = testList [1]; ListNode newList = DeepCopy (testList [0]); PrintList (testList [0]); Console.WriteLine ("------------------------------"); PrintList (newList); Console.WriteLine ("----Test regular List-----"); Node[] testList1 = new Node[]{new Node(1),new Node(2),new Node(3),new Node(4)}; for (int i = 0; i < testList1.Length-1; i++) { testList1 [i].Next = testList1 [i + 1]; } Node newHead = CopyRegular (testList1 [0]); PrintRegularList (testList1 [0]); Console.WriteLine ("------------------------------"); PrintRegularList (newHead); }