36.两个链表的第一个公共结点
题目描述
输入两个链表,找出它们的第一个公共结点。
题目解答
方法一:
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { //用两个指针扫描”两个链表“,最终两个指针到达null或者到达公共结点 ListNode p1=pHead1; ListNode p2=pHead2; while(p1!=p2){ p1=(p1==null ? pHead2:p1.next); p2=(p2==null ? pHead1:p2.next); } return p1; } }
方法二:
/* 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 length1=getListLength(pHead1); int length2=getListLength(pHead2); int lengthDiff=(length1>=length2 ? length1-length2:length2-length1); ListNode pLong=(length1>=length2 ? pHead1:pHead2); ListNode pShort=(length1>=length2? pHead2:pHead1); //先在长链表上走lengthDiff步,剩下的链表一般长,就不需要栈了 for(int i=0;i<lengthDiff;i++){ pLong=pLong.next; } //开始齐头并进,直到找到第一个公共结点 while((pLong!=pShort) && (pLong!=null) && (pShort!=null)){ pLong=pLong.next; pShort=pShort.next; } return pLong; } //求链表的长度 private int getListLength(ListNode pHead){ int length=0; ListNode pNode=pHead; while(pNode!=null){ length++; pNode=pNode.next; } return length; } }