首页 > 其他 > 详细

LeetCode——Intersection of Two Linked Lists

时间:2015-06-20 00:13:00      阅读:306      评论:0      收藏:0      [点我收藏+]

Description:

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.

求两个链表的相交的部分

/**
 * 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) {
        if(headA==null || headB==null)
            return null;
        ListNode aNode = headA;
        ListNode bNode = headB;
        int aLen = 0, bLen = 0;
        while(aNode != null) {
            aLen ++;
            aNode = aNode.next;
        }
        while(bNode != null) {
            bLen ++;
            bNode = bNode.next;
        }
        if(aNode != bNode) 
            return null;
        if(aLen > bLen) {
             for(int i = 0; i < aLen-bLen; i++)
                headA = headA.next;
        }
        else if(aLen < bLen) {
            for(int i=0; i<bLen-aLen; i++)
                headB = headB.next;
        }
        while(headA != headB) {
            headA = headA.next;
            headB = headB.next;
        }
        return headA;
    }
}

 

LeetCode——Intersection of Two Linked Lists

原文:http://www.cnblogs.com/wxisme/p/4589905.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!