题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
http://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
递归函数:
1.接收双链结构
2.走到每个链表的尾部,判断是否相等,相等则将尾部取出加到结果链表头,并重新记录新结果链表头
3.将去尾后的双链结构传给下一个函数
递归结束后,返回结果链表的头即可
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { static ListNode result=null; public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { if(pHead1==pHead2){ return pHead1; } fun(pHead1,pHead2); return result; } //递归函数 接收两个指针 public void fun(ListNode p1,ListNode p2) { if(p1==null||p2==null){ return; } //记录起点 ListNode initp1=p1; ListNode initp2=p2; //记录断点 ListNode mark = null,mark1=null; //p1走到尾n while (p1.next != null){ if(p1.next.next == null){ mark=p1; } p1=p1.next; } //p2走到尾 while (p2.next != null){ if(p2.next.next == null){ mark1=p2; } p2=p2.next; } //如果尾部相等 if(p1==p2){ //把尾部取出接到result上 头插 p1.next=result; result=p1; if(mark!=null) { mark.next = null; } if(mark1!=null) { mark1.next = null; } fun(initp1,initp2); } //如果尾部不等,不做操作 } }