LeetCode || Intersection of Two Linked Lists

来源:互联网 发布:动易cms 文件类型 编辑:程序博客网 时间:2024/06/05 17:46
/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {        ListNode* h1 = headA, *h2 = headB;        int len1 = 0, len2 = 0;        while(h1 != NULL)        {            len1++;            h1 = h1->next;        }        while(h2 != NULL)        {            len2++;            h2 = h2 ->next;        }                h1 = headA, h2 = headB;        while(len1 < len2)        {            len2--;            h2 = h2->next;        }        while(len1 > len2)        {            len1--;            h1 = h1->next;        }                while(h1 != NULL && h2 != NULL)        {            if(h1 == h2)                return h1;            else            {                h1 = h1->next;                h2 = h2->next;            }        }                return NULL;    }};

0 0
原创粉丝点击