java----两个链表寻找相交结点
问题描述寻找两个链表相交的结点解决思路①先求出两个链表的长度②将两链表长度相减, 将两链表中较长的链表走两个链表长度的差值的步数, 这时两链表长度相等.③两链表一步一步走, 比较结点是否相同.若相同则返回该节点;如果直到两个链表都走到结尾了, 还不相同, 则 两链表不相交.源代码public class GetIntersectionNode {public ListNode getInterse
·
- 问题描述
寻找两个链表相交的结点 - 解决思路
①先求出两个链表的长度
②将两链表长度相减, 将两链表中较长的链表走两个链表长度的差值的步数, 这时两链表长度相等.
③两链表一步一步走, 比较结点是否相同.
若相同则返回该节点;
如果直到两个链表都走到结尾了, 还不相同, 则 两链表不相交. - 源代码
public class GetIntersectionNode {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int length1 = getLength(headA);
int length2 = getLength(headB);
ListNode l1 = headA;
ListNode l2 = headB;
if (length1 > length2) {
int steps = length1 - length2;
for (int i = 0; i < steps; i++) {
l1 = l1.next;
}
} else {
int steps = length2 - length1;
for (int i = 0; i < steps; i++) {
l2 = l2.next;
}
}
while (l1 != null && l2 != null) {
if (l1 == l2) {
return l1;
}
l1 = l1.next;
l2 = l2.next;
}
return null;
}
public int getLength(ListNode head) {
int length = 0;
while (head != null) {
length++;
head = head.next;
}
return length;
}
}
更多推荐
已为社区贡献3条内容
所有评论(0)