复杂链表的复制

复杂链表的复制

http://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba

按顺序分两次复制,使用map存储clone的映射关系

  • 第一次,从头节点clone到尾节点,不复制random,并将原链表的地址与clone的新地址使用map映射
    tmp:=make(map[*RandomListNode]*RandomListNode)
      root := &RandomListNode{}
      h2 := root
      h1 := head
      for h1 != nil{
          h2.Next = &RandomListNode{h1.Label,nil,nil}
          tmp[h1] = h2.Next
          h2 = h2.Next
          h1 = h1.Next
      }
  • 第二次,从头节点clone到尾节点,复制random,从映射表中获取对应的clone地址,并赋值
    h2 = root.Next
      for head != nil{
          if head.Random != nil{
              h2.Random = tmp[head.Random]
    //             fmt.Println(tmp[head.Random].Label)
          }
          h2 = h2.Next
          head = head.Next
      }
全部评论

相关推荐

ResourceUt...:你是我见过最美的牛客女孩
晒一下我的毕业照
点赞 评论 收藏
分享
每晚夜里独自颤抖:这个在牛客不是老熟人了吗
点赞 评论 收藏
分享
投递长鑫存储等公司8个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务