欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

160. 相交链表

程序员文章站 2024-03-04 09:15:41
...

问题
编写一个程序,找到两个单链表相交的起始节点。

注意:

如果两个链表没有交点,返回 null.
在返回结果后,两个链表仍须保持原有的结构。
可假定整个链表结构中没有循环。
程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存。

例子
160. 相交链表
160. 相交链表
160. 相交链表
思路

  • 方法1
    遍历链表 A 并将每个结点的地址/引用存储在哈希表中。然后检查链表 B 中的每一个结点是否在哈希表中。若在,则为相交结点。
  • 方法2
    160. 相交链表
    a+b+None+c=c+b+None+a(当两个链表不想交时,b=0)
    一个从a开始走,走到头None,再走c,一个从c开始走,走到头None,再走a:一定会遇到,当不相交时(b=0),相遇的结点为None,当相交时,相遇的结点为相交结点
    代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
//方法1
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        Map<ListNode,Integer> map = new HashMap<>();
        while (headA!=null) {
            map.put(headA,map.getOrDefault(headA,0)+1);
            headA=headA.next;
        }
        while(headB!=null) {
            if (map.getOrDefault(headB,0)==1) return headB;
            headB=headB.next;
        }
        return null;
    }
}
//方法2
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null && headB == null) return null;
        ListNode a=headA, b=headB;
        while(headA!=headB){
            headA=headA!=null?headA.next:b;
            headB=headB!=null?headB.next:a;
        }
        return headA;
    }
}
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#方法1
class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        d=dict()
        while headA:
            d[headA]=1
            headA=headA.next
        
        while headB:
            if d.get(headB,0)==1:
                return headB
            headB=headB.next
        
        return None
#方法2
class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        if not headA or not headB: return None
        a=headA
        b=headB
        # is比较内存地址
        while a is not b:
            
            a = headB if a==None else a.next
            b = headA if b==None else b.next 
            
        return a
相关标签: leetcode easy