题解
思路:
- 复制节点,紧挨到到后面,1->2->3 ==> 1->1’->2->2’->3->3’
- 处理random指针
- 分离两个链表
代码
package main type Node struct { Val int Next *Node Random *Node } func copyRandomList(head *Node) *Node { if head == nil { return head } // 复制节点,紧挨到到后面 // 1->2->3 ==> 1->1'->2->2'->3->3' cur := head for cur != nil { clone := &Node{cur.Val, cur.Next, nil} temp := cur.Next cur.Next = clone cur = temp } //处理random指针 cur = head for cur != nil { if cur.Random != nil { cur.Next.Random = cur.Random.Next } cur = cur.Next.Next } //分离两个链表 cur = head cloneHead := cur.Next for cur != nil && cur.Next != nil { temp := cur.Next cur.Next = temp.Next cur = temp } return cloneHead } func main() { }