diff --git a/README.md b/README.md index 27468a88..670dc050 100755 --- a/README.md +++ b/README.md @@ -275,7 +275,7 @@ |0135|Candy||32.8%|Hard|| |0136|Single Number|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/0136.Single-Number)|66.4%|Easy|| |0137|Single Number II|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/0137.Single-Number-II)|53.5%|Medium|| -|0138|Copy List with Random Pointer||39.5%|Medium|| +|0138|Copy List with Random Pointer|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/0138.Copy-List-With-Random-Pointer)|39.5%|Medium|| |0139|Word Break||41.4%|Medium|| |0140|Word Break II||34.3%|Hard|| |0141|Linked List Cycle|[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/0141.Linked-List-Cycle)|42.2%|Easy|| diff --git a/leetcode/0138.Copy-List-With-Random-Pointer/138. Copy List With Random Pointer.go b/leetcode/0138.Copy-List-With-Random-Pointer/138. Copy List With Random Pointer.go new file mode 100644 index 00000000..1655092d --- /dev/null +++ b/leetcode/0138.Copy-List-With-Random-Pointer/138. Copy List With Random Pointer.go @@ -0,0 +1,46 @@ +package leetcode + +//执行用时:0 ms, 在所有 Go 提交中击败了100.00%的用户 +//内存消耗:3.4 MB, 在所有 Go 提交中击败了100.00%的用户 +type Node struct { + Val int + Next *Node + Random *Node +} + +func copyRandomList(head *Node) *Node { + if head == nil { + return nil + } + tempHead := copyNodeToLinkedList(head) + return splitLinkedList(tempHead) +} + +func splitLinkedList(head *Node) *Node { + cur := head + head = head.Next + for cur != nil && cur.Next != nil { + cur.Next, cur = cur.Next.Next, cur.Next + } + return head +} + +func copyNodeToLinkedList(head *Node) *Node { + cur := head + for cur != nil { + node := &Node{ + Val: cur.Val, + Next: cur.Next, + } + cur.Next, cur = node, cur.Next + + } + cur = head + for cur != nil { + if cur.Random != nil { + cur.Next.Random = cur.Random.Next + } + cur = cur.Next.Next + } + return head +} diff --git a/leetcode/0138.Copy-List-With-Random-Pointer/138. Copy List With Random Pointer_test.go b/leetcode/0138.Copy-List-With-Random-Pointer/138. Copy List With Random Pointer_test.go new file mode 100644 index 00000000..8c544247 --- /dev/null +++ b/leetcode/0138.Copy-List-With-Random-Pointer/138. Copy List With Random Pointer_test.go @@ -0,0 +1,7 @@ +package leetcode + +import "testing" + +func Test_Problem138(t *testing.T) { + +}