题目描述
输入两个链表,找出它们的第一个公共结点。(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)
解题思路
1->2->3->4 \
->7->8->9
5->6 /
根据链表特点,两个链表相遇之后重合
*1.双指针法:分别遍历两个链表得到链表长度 计算长度差k 让长链表先走k,然后两个链表一起走,相遇点即为所求
*2.借助栈:遍历两个链表,并入栈。然后出栈,当两个链表的出栈元素不一样的时候,代表链表分开了。
package list;
import java.util.Stack;
public class MyFindFirstCommonNode {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if (pHead1 == null || pHead2 == null) {
return null;
}
Stack<ListNode> s1 = new Stack<>();
Stack<ListNode> s2 = new Stack<>();
ListNode p1 = pHead1;
ListNode p2 = pHead2;
while (p1 != null) {
s1.push(p1);
p1 = p1.next;
}
while (p2 != null) {
s2.push(p2);
p2 = p2.next;
}
ListNode v1;
ListNode v2;
ListNode res = null;
while (!s1.empty() && !s2.empty()) {
v1 = s1.pop();
v2 = s2.pop();
if (v1.val != v2.val) {
break;
}
res = v1;
}
return res;
}
public static void main(String[] args) {
ListNode pHead1 = new ListNode(1);
ListNode b = new ListNode(2);
ListNode c = new ListNode(3);
ListNode d = new ListNode(4);
ListNode e = new ListNode(5);
ListNode pHead2 = new ListNode(6);
ListNode cc = new ListNode(7);
pHead1.next = b;
b.next = c;
c.next = d;
d.next = e;
pHead2.next = cc;
cc.next = d;
MyFindFirstCommonNode m = new MyFindFirstCommonNode();
System.out.println(m.FindFirstCommonNode(pHead1, pHead2).val);
}
}