一、题目
输入两个链表,找出它们的第一个公共结点。(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)
二、思路及代码实现
首先要搞清楚公共节点的含义:如果存在公共节点的话,那么两个链表从该节点之后的元素都是相同的,即两个相交的链表呈 Y 型。那就有两种思路:一种是从前往后比较,一种是从后往前比较。
方法一:从前往后
也就是比较两个链表前面不同的节点,直至找到第一个相同的节点为止。当然,这里两个链表的长度可能不同,这时,就要先让较长的链表先走一段(走两个链表的长度差),然后两个链表再一起遍历,才能同时到达公共节点。
代码如下:
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
ListNode node1 = pHead1;
ListNode node2 = pHead2;
if(node1 == null || node2 == null)
return null;
int l1 = getLength(node1);
int l2 = getLength(node2);
// 先让较长的链表走它们的长度差
if(l1 > l2){
int differ = l1 - l2;
while(differ-- != 0){
node1 = node1.next;
}
}else if(l1 < l2){
int differ = l2 - l1;
while(differ-- != 0){
node2 = node2.next;
}
}
// 开始一起同步走,直至找到第一个公共节点
while(node1 != node2){
node1 = node1.next;
node2 = node2.next;
}
return node1;
}
// 获取链表的长度
public int getLength(ListNode node){
int length = 0;
ListNode current = node;
if(current == null)
return length;
while(current != null){
length++;
current = current.next;
}
return length;
}
}
方法二:从后往前
如果两个链表存在公共节点的话,则两个链表从该节点之后的元素都是相同的。那么,从链表的末尾向前比较,最后一个相同的节点就是第一个公共节点。可以利用栈来实现。
代码如下:
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if(pHead1 == null || pHead2 == null)
return null;
LinkedList<ListNode> stack1 = new LinkedList<>();
LinkedList<ListNode> stack2 = new LinkedList<>();
// 链表1入栈
while(pHead1 != null){
stack1.push(pHead1);
pHead1 = pHead1.next;
}
// 链表2入栈
while(pHead2 != null){
stack2.push(pHead2);
pHead2 = pHead2.next;
}
// 出栈,从后往前比较
ListNode common = null;
while(!stack1.isEmpty() && !stack2.isEmpty() && stack1.peek() == stack2.peek()){
stack1.pop();
common = stack2.pop();
}
return common;
}
}