题目:输入两个链表,找出它们的第一个公共节点。
链接:https://www.nowcoder.com/questionTerminal/6ab1d9a29e88450685099d45c9e31e46
来源:牛客网
思路一:栈(后进先出)。分别把两个链表的节点放入两个栈里,这样两个链表的尾节点就位于两个栈的栈顶,接下来比较两个栈顶的节点是否相同。如果相同,则把栈顶弹出接着比较下一个栈顶,直到找到最后一个相同的节点。
package offer;
import java.util.Stack;
public class Solution52 {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if (pHead1 == null || pHead2 == null)
return null;
Stack<ListNode> stack1 = new Stack<ListNode>();
Stack<ListNode> stack2 = new Stack<ListNode>();
while (pHead1 != null) {
stack1.push(pHead1);
pHead1 = pHead1.next;
}
while (pHead2 != null) {
stack2.push(pHead2);
pHead2 = pHead2.next;
}
ListNode common = null;
while (!stack1.isEmpty() && !stack2.isEmpty() && stack1.peek() == stack2.peek()) {
stack2.pop();
common = stack1.pop();
}
return common;
}
}
思路二:先分别遍历出两个链表的节点数,第一个链表比第二个多出n个,则再次遍历的时候,让第一个链表先走n步,之后齐头并进,直到找到它们第一个相同的节点。
package offer;
import java.util.Stack;
public class Solution52 {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
ListNode current1 = pHead1;
ListNode current2 = pHead2;
if (pHead1 == null || pHead2 == null)
return null;
// 获取两个链表的长度
int length1 = 0, length2 = 0;
while (pHead1 != null) {
length1++;
pHead1 = pHead1.next;
}
while (pHead2 != null) {
length2++;
pHead2 = pHead2.next;
}
// 长链表先走若干步
if (length1 >= length2) {
int len = length1 - length2;
while (len > 0) {
current1 = current1.next;
len--;
}
} else if (length1 < length2) {
int len = length2 - length1;
while (len > 0) {
current2 = current2.next;
len--;
}
}
// 两个链表齐头并进
while (current1 != current2) {
current1 = current1.next;
current2 = current2.next;
}
return current1;
}
}