相交链表( LeetCode 160 )

题目链接

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

代码实现

java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
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++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值