leetcode160~Intersection of Two Linked Lists

来源:互联网 发布:mac 扩展磁盘 找不到 编辑:程序博客网 时间:2024/05/20 01:12

Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

A:          a1 → a2                   ↘                     c1 → c2 → c3                   ↗            B:     b1 → b2 → b3

begin to intersect at node c1.
Notes:

If the two linked lists have no intersection at all, return null.
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Your code should preferably run in O(n) time and use only O(1) memory.

public class IntersectionofTwoLinkedLists {    /*     * 统计两个链表的长度,然后使用俩指针,让长链表的指针先走lenA-lenB步,然后再一起走     */    public ListNode getIntersectionNode1(ListNode headA, ListNode headB) {        if(headA==null || headB==null) return null;        int lenA = getLength(headA);        int lenB = getLength(headB);        //长链表先走len1-len2步        while(lenA>lenB) {            headA = headA.next;            lenA--;        }        while(lenA<lenB) {            headB = headB.next;            lenB--;        }        //同时遍历        while(headA!=headB) {            headA = headA.next;            headB = headB.next;        }        return headA;    }    private int getLength(ListNode head) {        int len = 0;        while(head!=null) {            head = head.next;            len++;        }        return len;    }    //一个链表遍历到尾部时,从另外一个链表的头部开始再次遍历,最终会相遇    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {        if(headA==null || headB==null) return null;        ListNode curA = headA;        ListNode curB = headB;        while(curA!=curB) {            curA = curA==null? headB:curA.next;            curB = curB==null? headA:curB.next;        }        return curA;    }}
0 0
原创粉丝点击