380

来源:互联网 发布:网络摄像头怎么安装 编辑:程序博客网 时间:2024/05/14 20:06

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;            }  }


原创粉丝点击