Intersection of Two Linked Lists

来源:互联网 发布:淘宝网平板电脑价格 编辑:程序博客网 时间:2024/06/06 14:52
/** * 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) {        if(headA==NULL||headB==NULL) return NULL;        ListNode *tempA=headA,*tempB=headB;        int lenA=0,lenB=0,dlen;        while(tempA!=NULL) {lenA++;tempA=tempA->next;}        while(tempB!=NULL) {lenB++;tempB=tempB->next;}        dlen=lenA-lenB>0?lenA-lenB:lenB-lenA;        if(lenA>=lenB){            tempA=headA;tempB=headB;        }        else {tempA=headB;tempB=headA;}        while(dlen>0) {tempA=tempA->next;dlen--;}        while(tempA!=NULL)        {            if(tempA==tempB) return tempA;            else{tempA=tempA->next;tempB=tempB->next;}        }        return NULL;    }};

0 0
原创粉丝点击