栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

相交链表( LeetCode 160 )

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

相交链表( LeetCode 160 )

题目链接

https://leetcode.cn/problems/intersection-of-two-linked-lists-lcci/

代码实现 java
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA==null||headB==null)
        {
            return null;
        }

        ListNode pointA=headA;
        ListNode pointB=headB;

        while(pointA!=pointB)
        {
            pointA=pointA==null?headB:pointA.next;
            pointB=pointB==null?headA:pointB.next;
        }
        return pointA;
    }
}
c++

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        if(headA==NULL||headB==NULL)
        {
            return NULL;
        }

        ListNode *pointA=headA;
        ListNode *pointB=headB;

        while(pointA!=pointB)
        {
            pointA=pointA==NULL?headB:pointA->next;
            pointB=pointB==NULL?headA:pointB->next;
        }
        return pointA;
        
    }
};
python
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        if headA==None or headB==None:
            return None

        pointA=headA
        pointB=headB

        while pointA != pointB:
            # 指针 pointA 一开始在链表 A 上遍历,当走到链表 A 的尾部即 null 时,跳转到链表 B 上 
            if pointA == None:
                # 指针 pointA 跳转到链表 B 上  
                pointA = headB
            else:
                # 否则的话 pointA 不断的向后移动
                pointA = pointA.next
            # 指针 pointB 一开始在链表 B 上遍历,当走到链表 B 的尾部即 null 时,跳转到链表 A 上 
            if pointB == None:
                # 指针 pointA 跳转到链表 B 上  
                pointB = headA
            else:
                # 否则的话 pointB 不断的向后移动
                pointB = pointB.next

        # 1、此时,pointA 和 pointB 指向那个相交的节点,返回任意一个均可
        # 2、此时,headA 和 headB 不相交,那么 pointA 和 pointB 均为 null,也返回任意一个均可
        return pointA
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/880073.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号