输入两个链表,找出它们的第一个公共结点。
思路一:因为如果两个链表有公共节点的话,则他们的尾部是一样的,用两个栈来存两个链表的节点,开始弹出的值是相同的,弹到不同的时候,就截至,其下一节点就是所求第一个公共节点。
//最快捷的方法
public static ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
ListNode p1 = pHead1;
ListNode p2 = pHead2;
while(p1!=p2){
p1 = (p1==null)?pHead2:p1.next;
p2 = (p2==null)?pHead1:p2.next;
}
return p1;
}
package cn.com.jianzhioffer;
import java.util.Stack;
public class Solution37 {
public static class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
public boolean equals(ListNode pNode1, ListNode pNode2) {
if (pNode1.val == pNode2.val)
return true;
return false;
}
}
public static 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>();
ListNode pNode1 = pHead1;
ListNode pNode2 = pHead2;
while (pNode1 != null) {
stack1.push(pNode1);
pNode1 = pNode1.next;
}
while (pNode2 != null) {
stack2.push(pNode2);
pNode2 = pNode2.next;
}
pNode1 = stack1.pop();
pNode2 = stack2.pop();
while (pNode1.equals(pNode2) && (!stack1.empty()) && (!stack2.empty())) {
pNode1 = stack1.pop();
pNode2 = stack2.pop();
}
if (stack1.empty() || stack2.empty()) {
return pNode1;
} else {
return pNode1.next;
}
}
public static void main(String[] args) {
ListNode pHead1 = new ListNode(1);
ListNode pNode2 = new ListNode(2);
ListNode pNode3 = new ListNode(3);
pHead1.next = pNode2;
pNode2.next = pNode3;
ListNode pHead2 = new ListNode(4);
pHead2.next = pNode2;
System.out.println(FindFirstCommonNode(pHead1, pHead2).val);
}
}