自己的想法:两个链表的第一个公共节点在链表的后面 -> 要从后往前判断,相等则继续向前 -> 如何从后向前移动?比如从最后一个节点找到倒数第二个节点 -> 第一次遍历时把链表反转(×)
正解:使用栈,后进先出,遍历链表时把每个节点入栈,最后从栈顶开始比较,满足从后向前判断,同时保证链表的节点顺序。
另一种解法:长的链表先走x步,使剩下的链表长度和另一个链表长度相等,从此处向后比较。代码如下:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if (pHead1 == null || pHead2 == null) {
return null;
}
int len1 = 0, len2 = 0;
ListNode phead1 = pHead1, phead2 = pHead2;
while (phead1 != null) {
len1++;
phead1 = phead1.next;
}
while (phead2 != null) {
len2++;
phead2 = phead2.next;
}
if (len1 < len2) {
int k = len2 - len1;
while (k > 0) {
pHead2 = pHead2.next;
k--;
}
} else {
int k = len1 - len2;
while (k > 0) {
pHead1 = pHead1.next;
k--;
}
}
while (pHead1 != null) {
if (pHead1 == pHead2) {
return pHead1;
} else {
pHead1 = pHead1.next;
pHead2 = pHead2.next;
}
}
return null;
}
}
京公网安备 11010502036488号