python链表——链表交叉

 

思路

1. 首尾相接法,如果交叉,则尾结点相同

2. 遍历获得尾结点,以及两个链表长度n1, n2,并将长链向前移动 |n1-n2| 步,这样同时向前遍历后,第一次相遇的点就是交叉点了。

代码

def isIntersect(head1, head2):
    if head1 is None or head2 is None or head1.next is None or head2.next is None:
        return None
    end1 = head1.next
    end2 = head2.next
    n1 = 0
    n2 = 0
    # 找到尾结点
    while end1.next:
        end1 = end1.next
        n1 += 1
    while end2.next:
        end2 = end2.next
        n2 += 1
    # 尾结点相等,说明有交叉
    if end1 == end2:
        # 长链向前移动|n1-n2|步
        if n1 > n2:
            while n1 > n2:
                head1 = head1.next
                n1 -= 1
        else:
            while n1 < n2:
                head2 = head2.next
                n2 -= 1
        # 同时移动,第一次相遇处,即为交叉点
        while head1 != head2:
            head1 = head1.next
            head2 = head2.next
        return head1
    else:
        return None


# 测试
test_head1 = Node(None)
test_head2 = Node(None)

cur1 = test_head1
i = 1
tmp = None
p = None
while i < 8:
    tmp = Node(i)
    tmp.next = None
    cur1.next = tmp
    cur1 = tmp
    if i == 5:
        p = tmp
    i += 1

cur2 = test_head2
j = 1
while j < 5:
    tmp = Node(j)
    cur2.next = tmp
    cur2 = tmp
    j += 1

# 5的位置为交叉点
cur2.next = p


interNode = isIntersect(test_head1, test_head2)
print(interNode)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值