两个长度不一定相等的链表,找出其第一个公共节点。
/*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 p1=pHead1; ListNode p2=pHead2; while(p1!=p2){ p1=(p1==null?pHead2:p1.next); p2=(p2==null?pHead1:p2.next); } return p1; }*/ //第二种方法 public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { int len1=getListLength(pHead1); int len2=getListLength(pHead2); int dis=0; ListNode longHead=null,shortHead=null; //先分辨链表的长短 if(len1>len2){ dis=len1-len2; longHead=pHead1; shortHead=pHead2; }else{ dis=len2-len1; longHead=pHead2; shortHead=pHead1; } //先检测较长链表比短链表多出来的那些节点 while(dis>0){ if(longHead==shortHead){ return longHead; } dis--; longHead=longHead.next; } //至此两个链表将会同时到达末尾 while(longHead!=null){ if(longHead==shortHead){ return longHead; } longHead=longHead.next; shortHead=shortHead.next; } return longHead; } //计算列表长度 public int getListLength(ListNode phead){ ListNode head=phead; int count=0; while(head!=null){ count++; head=head.next; } return count; }}