题目:
输入两个链表,找出它们的第一个公共结点。
思路:
方法1:
利用栈辅助
先把两个链表依次装到两个栈中,然后比较两个栈的栈顶结点是否相同,如果相同则出栈,如果不同,那最后相同的结点就是我们要的,并返回。
方法2:
由于是单链表,当出现公共结点以后,后面部分均相同。
1、当链表长度相同时,两个链表从头开始同步遍历,一定会找到第一个共同的结点;
2、当链表长度不同时,先让长链表遍历多出的那部分,再同时遍历。
程序:
程序1:
import java.util.Stack;
public class ListNode{
int val;
ListNode next;
ListNode(int val){
this.val = val;
}
}
public class subject36 {
public static ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if(pHead1 == null || pHead2 == null) {
return null;
}
Stack<ListNode> s1 = new Stack<ListNode>();
Stack<ListNode> s2 = new Stack<ListNode>();
while(pHead1 != null) {
s1.push(pHead1);
pHead1 = pHead1.next;
}
while(pHead2 != null) {
s2.push(pHead2);
pHead2 = pHead2.next;
}
ListNode res = null;
while(! s1.isEmpty() && ! s2.isEmpty() && s1.peek() == s2.peek()) {
s1.pop();
res = s2.pop();
}
return res;
}
}
程序2:
public class ListNode{
int val;
ListNode next;
ListNode(int val){
this.val = val;
}
}
public class subject36 {
public static ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
int size1 = findListLength(pHead1);
int size2 = findListLength(pHead2);
if(size1 == 0 || size2 == 0) {
return null;
}
if(size1 > size2) {
pHead1 = walkStepNode(pHead1, size1 - size2);
}
if(size1 < size2) {
pHead2 = walkStepNode(pHead1, size2 - size1);
}
while(pHead1 != null) {
if(pHead1 == pHead2) {
return pHead1;
}
//同时遍历链表
pHead1 = pHead1.next;
pHead2 = pHead2.next;
}
return null;
}
//求链表长度
public static int findListLength(ListNode p) {
int count = 0;
while(p != null) {
p = p.next;
count ++;
}
return count;
}
//先遍历长链表,直到与短链表长度相同
public static ListNode walkStepNode(ListNode p, int step) {
while(step != 0) {
p = p.next;
step --;
}
return p;
}
}