380 - 两个链表的交叉

5.20

先遍历一遍链表,存入ArrayList中。

然后从后向前找到相同的地方,在选取较短的链表从前向后遍历找到节点。

还是要注意 要使用equals 不要使用==。

郁闷,现在一个题总要提交很多很多遍才可以AC。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;      
 *     }
 * }
 */
public class Solution {
    /**
     * @param headA: the first list
     * @param headB: the second list
     * @return: a ListNode 
     */
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        // Write your code here
        if(headA == null || headB == null){
            return null;
        }
        ArrayList<Integer> listA = new ArrayList<Integer>();
        ArrayList<Integer> listB = new ArrayList<Integer>();
        ListNode tmpA = headA;
        ListNode tmpB = headB;
        while(tmpA != null){
            listA.add(tmpA.val);
            tmpA = tmpA.next;
        }
        while(tmpB != null){
            listB.add(tmpB.val);
            tmpB = tmpB.next;
        }
        int la = listA.size() - 1;
        int lb = listB.size() - 1;
        //System.out.println("前la:" + la + ";lb:" + lb);
        while(la >= 0 && lb >= 0){
            //System.out.println("listA.get(la):" + listA.get(la) + ";listB.get(lb):" + listB.get(lb));
            if(listA.get(la).equals(listB.get(lb))){
                la --;
                lb --;
            }
            else{
                break;
            }
        }
        //System.out.println("后la:" + la + ";lb:" + lb);
        ListNode res = null;
        if(la == -1){
            return headA;
        }
        if(lb == -1){
            return headB;
        }
        if(la <= lb){
            res = headA;
            while(la >= 0 && res.next != null){
                res = res.next;
                la --;
            } 
        }
        else{
            res = headB;
            while(lb >= 0 && res.next != null){
                res = res.next;
                lb--;
            }
        }
        return res;
        
    }  
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值