1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| package main
import ( "fmt" )
type ComplexListNode struct { Val int Next *ComplexListNode Sibling *ComplexListNode }
func CloneComplexList(head *ComplexListNode) *ComplexListNode { if head == nil { return nil } m := make(map[*ComplexListNode]*ComplexListNode) cur := head for cur != nil { if _, ok := m[cur]; !ok { m[cur] = &ComplexListNode{cur.Val, nil, nil} } if cur.Next != nil { if _, ok := m[cur.Next]; !ok { m[cur.Next] = &ComplexListNode{cur.Next.Val, nil, nil} } m[cur].Next = m[cur.Next] } if cur.Sibling != nil { if _, ok := m[cur.Sibling]; !ok { m[cur.Sibling] = &ComplexListNode{cur.Sibling.Val, nil, nil} } m[cur].Sibling = m[cur.Sibling] } cur = cur.Next } return m[head] }
func printList(head *ComplexListNode){ for head != nil{ fmt.Printf("当前节点: %d 兄弟节点: %d \t", head.Val, head.Sibling.Val) head = head.Next } }
func main() { l3 := &ComplexListNode{3, nil, nil} l2 := &ComplexListNode{2, l3, nil} l1 := &ComplexListNode{1, l2, nil} l1.Sibling = l3 l2.Sibling = l2 l3.Sibling = l1 fmt.Println("复制前 --------- ") printList(l1) fmt.Println() fmt.Println("复制后 --------- ") printList(CloneComplexList(l1)) }
复制前 --------- 当前节点: 1 兄弟节点: 3 当前节点: 2 兄弟节点: 2 当前节点: 3 兄弟节点: 1 复制后 --------- 当前节点: 1 兄弟节点: 3 当前节点: 2 兄弟节点: 2 当前节点: 3 兄弟节点: 1
Process finished with exit code 0
|