LeetCode(160): Intersection of Two Linked Lists

Intersection of Two Linked Lists:

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.

题意:找出给定的两个链表,链表开始相交的交点。

思路:先分别遍历两个链表获取两个链表的长度,len1和len1,并定义两个指针p和q,如果len1==len2则两个指针分别同时指向链表的首节点;如果len1>len2或len1<len2,则指针p或q,指向第|len1-len2|个节点,然后在进行判断。

代码:

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
         int a_len = 0;
         int b_len = 0;
         ListNode p = headA;
         ListNode q = headB;
         while(p!=null){
             a_len++;
             p=p.next;
         }
         p = headB;
         while(p!=null){
             b_len++;
             p=p.next;
         }
         if(a_len==0||b_len==0){
             return null;
         }
         p = headA;
         q = headB;
         int sub_len = a_len - b_len;
         if(sub_len!=0){
             if(sub_len>0){
                 while(sub_len>0){
                     p = p.next;
                     sub_len --;
                 }
             }else{
                 sub_len = -1*sub_len;
                 while(sub_len>0){
                     q= q.next;
                     sub_len--;
                 }
             }
         }
         while(p!=null&&q!=null){
             if(p==q){
                 return p;
             }else{
                 p = p.next;
                 q = q.next;
             }
         }
         return null;
    }
posted @ 2016-01-14 19:26  Lewisr  阅读(134)  评论(0编辑  收藏  举报