LeetCode随笔之链表

来源:互联网 发布:跟兄弟连学php 电子书 编辑:程序博客网 时间:2024/06/15 05:43
  1. 输入两个链表,找出它们的第一个公共结点。
/*找出2个链表的长度,然后让长的先走两个链表的长度差,然后再一起走(因为2个链表用公共的尾部)*/class Solution {public:    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {        int p1Len=findLen(pHead1);        int p2Len=findLen(pHead2);        p1Len>p2Len? pHead1=walkStep(pHead1,p1Len-p2Len):pHead2=walkStep(pHead2,p2Len-p1Len);        while(pHead1)        {            if(pHead1==pHead2) return pHead1;            pHead1=pHead1->next;pHead2=pHead2->next;        }        return pHead1;    }    ListNode* walkStep(ListNode* pHead,int step){        while(step){pHead=pHead->next;step--;}        return pHead;    }    int findLen(ListNode* pHead){        if(!pHead) return 0;        int sum=1;        while(pHead=pHead->next)sum++;        return sum;    }};