예제 #1
0

# 找到环的入口处
def FindLoopNode(head, meetNode: Node):
    first = head.next
    second = meetNode
    while first != second:
        first = first.next
        second = second.next

    return first


if __name__ == '__main__':
    head = List2Link([i for i in range(10)])
    ShowLink(head)

    # 构造 环
    p = head.next
    while p.next is not None:
        p = p.next

    print(p.data, "->", head.next.next.next.data)
    p.next = head.next.next.next

    meetNode = IsLoop(head)
    print('meetNode: ', meetNode.data if meetNode is not None else "None")
    if meetNode is not None:
        loopNode = FindLoopNode(head, meetNode)
        print('入口: ', loopNode.data)
예제 #2
0
    if cur1.data > cur2.data:
        head = h2
        cur = cur2
        cur2 = cur2.next
    else:
        head = h1
        cur = cur1
        cur1 = cur1.next

    while (cur1 and cur2) is not None:
        if cur1.data < cur2.data:
            cur.next = cur1
            cur = cur1
            cur1 = cur1.next
        else:
            cur.next = cur2
            cur = cur2
            cur2 = cur2.next

    if cur1 is not None:
        cur.next = cur1
    if cur2 is not None:
        cur.next = cur2
    return head


if __name__ == '__main__':
    h1 = List2Link([i for i in range(20, 30, 2)])
    h2 = List2Link([i for i in range(20, 30, 3)])
    ShowLink(Merge(h1, h2))
예제 #3
0
        if n1 > n2:
            while n1 - n2 > 0:
                h1 = h1.next
                n1 -= 1
        if n1 < n2:
            while n2 - n1 > 0:
                h2 = h2.next
                n2 -= 1

        # 2个链表同时前进, 找到相同节点
        while h1 != h2:
            h1 = h1.next
            h2 = h2.next
        return h1
    else:
        return None


if __name__ == '__main__':
    h1 = RandHead(2)
    h2 = RandHead(2)
    tp = RandHead(2)

    h1.next.next.next = tp.next
    h2.next.next.next = tp.next

    ShowLink(h1)
    ShowLink(h2)

    result = IsIntersect(h1, h2)
    print(result.data if result is not None else "None")
예제 #4
0
            p.next = tp
            p = tp

            p2 = p2.next
    # p1 长度 >= p2
    if p2 is None:
        while p1 is not None:
            sums = p1.data + c
            tp = Node(sums % 10)
            c = sums // 10
            p.next = tp
            p = tp

            p2 = p1.next

    # 如果还有进位
    if c == 1:
        tp = Node(1)
        p.next = tp

    return resultHead


if __name__ == '__main__':
    # 321
    h1 = List2Link([1, 2, 3])
    # 9789
    h2 = List2Link([9, 8, 7, 9])
    result = Add(h1, h2)
    ShowLink(result)