# 【Leetcode】Intersection of Two Linked Lists

500人阅读 评论(0)

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.

1、暴力迭代两个链表结点比较相等，时间复杂度O(n^2)
3、从表尾对齐两链表，截去长的链表多余部分，使得两链表长度相等，然后每次移动一个结点，判断指针是否相等

public int getListLength(ListNode head) {
int length = 0;
while (p != null) {
length++;
p = p.next;
}
return length;
}

public ListNode getListNode(ListNode head, int count) {
int i = count;
while (--i > 0 && p != null) {
p = p.next;
}
return p;
}

if (alength > blength) {
l1 = getListNode(headA, (alength - blength + 1));
} else {
l2 = getListNode(headB, (blength - alength + 1));
}
while (l1 != null && l2 != null) {
if (l1 == l2)
return l1;
l1 = l1.next;
l2 = l2.next;
}
return null;
}

个人资料
等级：
访问量： 57万+
积分： 8679
排名： 2734
博客专栏
 Leetcode题解java版 文章：289篇 阅读：494379
最新评论