160. 相交链表

题目:https://leetcode-cn.com/problems/intersection-of-two-linked-lists/

自己的方法:暴力方法:

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode tempb=new ListNode(-999);
        while( headA!=null)
        {
            ListNode tempa=headA;
            for(tempb=headB;tempb!=null;tempb=tempb.next)
            {
                if(tempb==tempa)
                {
                    return tempb;
                }
            }

            headA=headA.next;
        }
        return null;
    }
}

其它方法:

解一:

计算两个链表各自长度,长度之差为 diff
让较长链表先走 diff 步
长短链表再同步往前走,在第一个相同节点停下
如果走完了链表没有相遇,说明两个链表不相交

class Solution:
    def getIntersectionNode(self, L1: ListNode, L2: ListNode) -> ListNode:

        def length(L):
            n = 0
            while L:
                n += 1; L = L.next
            return n 
        
        len1, len2 = length(L1), length(L2)
        if len1 > len2:
            L1, L2 = L2, L1
        for _ in range(abs(len1 - len2)):
            L2 = L2.next
        while L1 and L2 and L1 is not L2:
            L1, L2 = L1.next, L2.next
        return L1

解二:

  • 长短链表相互拼接,遇到相同节点跳出循环,该节点即为相交节点
class Solution:
    def getIntersectionNode(self, L1: ListNode, L2: ListNode) -> ListNode:
        h1, h2 = L1, L2
        while h1 is not h2:
            h1 = h1.next if h1 else L2
            h2 = h2.next if h2 else L1
        return h1
原文地址:https://www.cnblogs.com/William-xh/p/13637215.html