输入两个链表l1和l2,找出它们的第一个公共节点。
思路:单链表如果有公共节点,肯定为Y型,从末尾扫描到头可找出第一个不相同的即可,l1和l2压栈,从尾开始弹出,第一个不相同的即为答案,时间复杂度O(m+n),需要额外空间复杂度O(m+n);
若知道两个链表长度,长的先走几步,然后两链表同步向前,找出第一个相同的节点,这种不需要额外空间,时间复杂度O(m+n),代码如下
public class Solution {
public static void main(String[] args) {
ListNode a1 = new ListNode(1);
ListNode a2 = new ListNode(2);
ListNode a3 = new ListNode(3);
a1.next = a2;
a2.next = a3;
ListNode b1 = a2;
ListNode b2 = a3;
ListNode s = findFirstCommonNode(a1, b1);
if (s == null) {
System.out.println("kong");
} else {
System.out.println(s.val);
}
}
public static ListNode findFirstCommonNode(ListNode l1, ListNode l2) {
int lengthL1 = ListNodeLength(l1);
int lengthL2 = ListNodeLength(l2);
int diff = lengthL1 - lengthL2;
ListNode longList = l1;
ListNode shortList = l2;
if (diff < 0) {
diff = -diff;
longList = l2;
shortList = l1;
}
for (int i = 0; i < diff; i++) {
longList = longList.next;
}
// 这里判断相同的条件是==,没有复写equals
while (longList != null && shortList != null && longList != shortList) {
longList = longList.next;
shortList = shortList.next;
}
return longList;
}
public static int ListNodeLength(ListNode head) {
int n = 0;
while (head != null) {
head = head.next;
n++;
}
return n;
}
}