leetcode 链表相交

上题目链接:

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

这题目的介绍跟shit一样看不懂,才发现链表节点也能判断是否相等的。

上代码

/**
 * 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) {
        ListNode tempA = headA;
        ListNode tempB = headB;
        int lenA = 0, lenB = 0;
        while(tempA != null){
            tempA = tempA.next;
            lenA++;
        }
        while(tempB != null){
            tempB = tempB.next;
            lenB++;
        }
        int sub, count = 0;
        ListNode curA = headA;
        ListNode curB = headB;
        if(lenA >= lenB){
            sub = lenA - lenB;
            while(sub-- > 0){
                curA = curA.next;
            }
            while(curA != null){
                if(curA == curB){
                    return curA;   
                } 
                curA = curA.next;
                curB = curB.next;
            }
            return null;
        }else{
            sub = lenB - lenA;
            while(sub-- > 0){
                curB = curB.next;
            }

            while(curB !=null){
                if(curB == curA){
                    return curA;
                } 
                curA = curA.next;
                curB = curB.next;
            }
            return null; 
        }
    }
}

代码意思很简单,先求出A和B链表的长度,比大小,把两个链表右对齐,然后一个个节点判断是否相等往右移,直到结束,如果遍历完还没有相等的节点,就返回null。

这里节点相等并不是值相等,而是节点的地址相等,至于题目例子中为什么不是从1节点开始,是因为题目设置了1节点是不同地址的两个节点。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值