LeetCode题解:Intersection of Two Linked Lists

来源:互联网 发布:数据分享网站 编辑:程序博客网 时间:2024/06/09 02:25

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.

题意:找到两个链表的交点

解决思路:两个链表在同一个起点开始向下找

代码:

public class Solution {    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {        int lenA = length(headA);        int lenB = length(headB);        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;    }    public int length(ListNode head){        int length = 0;        ListNode node = head;        while(node != null){            ++length;            node = node.next;        }        return length;    }}
0 0
原创粉丝点击