JZ52 两个链表的第一个公共结点
解法一
import java.util.*;
/*
public class ListNode {int val;ListNode next = null;ListNode(int val) {this.val = val;}
}*/
public class Solution {public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {int lenA = 0;int lenB = 0;int len = 0;ListNode pl = pHead1;ListNode ps = pHead2;while(pl!=null) {lenA++;pl = pl.next;}while(ps!=null) {lenB++;ps = ps.next;}len = lenA - lenB;pl = pHead1;ps = pHead2;if(len < 0) {pl = pHead2;ps = pHead1;len = lenB - lenA;}if(pl==null || ps == null) return null;while(len > 0) {pl = pl.next;len--;}while(pl!=ps) {pl = pl.next;ps = ps.next;}return pl;}
}
解法2:
import java.util.*;
/*
public class ListNode {int val;ListNode next = null;ListNode(int val) {this.val = val;}
}*/
public class Solution {public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {ListNode cur1 = pHead1;ListNode cur2 = pHead2;while(cur1!= cur2) {cur1 = cur1 != null ? cur1.next : pHead2;cur2 = cur2 != null ? cur2.next : pHead1;}return cur1;}
}