剑指Offer-35.两个链表的第一个公共结点(C++/Java)
作者:互联网
题目:
输入两个链表,找出它们的第一个公共结点。
分析:
先统计两个链表的长度,计算他们的差值,然后将两个链表对齐,再去寻找公共节点即可。
程序:
C++
class Solution { public: ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) { int d1 = 0; int d2 = 0; int d = 0; ListNode* p1 = pHead1; ListNode* p2 = pHead2; while(p1 != nullptr){ p1 = p1->next; d1++; } while(p2 != nullptr){ p2 = p2->next; d2++; } if(d1 < d2){ d = d2 - d1; while(d--){ pHead2 = pHead2->next; } } else{ d = d1 - d2; while(d--){ pHead1 = pHead1->next; } } while(pHead1 != nullptr && pHead2 != nullptr){ if(pHead1 == pHead2){ return pHead1; } pHead1 = pHead1->next; pHead2 = pHead2->next; } return nullptr; } };
Java
public class Solution { public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { int d1 = 0; int d2 = 0; int d = 0; ListNode p1 = pHead1; ListNode p2 = pHead2; while(p1 != null){ p1 = p1.next; d1++; } while(p2 != null){ p2 = p2.next; d2++; } if(d1 < d2){ d = d2 - d1; while(d-- != 0){ pHead2 = pHead2.next; } } else{ d = d1 - d2; while(d-- != 0){ pHead1 = pHead1.next; } } while(pHead1 != null && pHead2 != null){ if(pHead1 == pHead2){ return pHead1; } pHead1 = pHead1.next; pHead2 = pHead2.next; } return null; } }
标签:ListNode,Offer,35,next,链表,pHead1,pHead2,d2,d1 来源: https://www.cnblogs.com/silentteller/p/11991872.html