leetcode 160. Intersection of Two Linked Lists

来源:互联网 发布:吴闲云水浒知乎 编辑:程序博客网 时间:2024/05/22 05:26
/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    int back(ListNode*head){       int len = 0;       while(head!=NULL){           len++;           head = head->next;       }       return len;    }    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {        int len1 = back(headA),len2 = back(headB);        ListNode*a=headA,*b=headB;        if(len1 > len2){            while(len2 < len1){                a=a->next;                len2++;            }        }        else {            while(len1 < len2){                b=b->next;                len1++;            }        }        while(a != b && a != NULL){            a = a->next;            b = b->next;        }                return a;    }};

0 0