From 1780117bd64f42c6ab0103d8f7132fc7862774c5 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Sat, 25 May 2024 21:41:53 +0800 Subject: [PATCH] 20240525 Finished --- LeetCodeSharp/Problems/Solution138.cs | 87 +++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 LeetCodeSharp/Problems/Solution138.cs diff --git a/LeetCodeSharp/Problems/Solution138.cs b/LeetCodeSharp/Problems/Solution138.cs new file mode 100644 index 0000000..eadf4fa --- /dev/null +++ b/LeetCodeSharp/Problems/Solution138.cs @@ -0,0 +1,87 @@ +// [138] Copy List with Random Pointer + +using System.Collections.Generic; + +namespace LeetCodeSharp.Problems138 +{ + // Submission codes start here + + /* +// Definition for a Node. +public class Node { + public int val; + public Node next; + public Node random; + + public Node(int _val) { + val = _val; + next = null; + random = null; + } +} +*/ + public class Node + { + public int val; + public Node next; + public Node random; + + public Node(int _val) + { + val = _val; + next = null; + random = null; + } + } + + public class Solution + { + private readonly List _nodes = new List(); + + public Node CopyRandomList(Node head) + { + _nodes.Clear(); + + Node newHead = null; + Node newNow = null; + Node now = head; + + while (now != null) + { + Node newNode = new Node(now.val); + now.val = _nodes.Count; + newNode.random = now.random; + _nodes.Add(newNode); + + if (newHead == null) + { + newHead = newNode; + newNow = newNode; + } + else + { + newNow.next = newNode; + newNow = newNode; + } + + now = now.next; + } + + newNow = newHead; + + while (newNow != null) + { + if (newNow.random != null) + { + newNow.random = _nodes[newNow.random.val]; + } + + newNow = newNow.next; + } + + return newHead; + } + } + + // Submission codes end here +} \ No newline at end of file