Intersection of Two Linked Lists

来源:互联网 发布:mac换主板序列号还在吗 编辑:程序博客网 时间:2024/06/07 07:01

这道题找两个链表的交叉点,要点是找两个链表的长度差。找到长度差,然后去掉这个差两个链表一起走,就会相遇。有交叉点就在交叉点相遇,没有的话就是NULL。这个一个走到尾就到另一个的头结点的作用,就是把这个两个链表的差给去掉了。

/** * 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 *l1=headA;        ListNode *l2=headB;        if(l1==NULL||l2==NULL) return NULL;        while(l1!=l2)        {           l1=l1?l1->next:headB;           l2=l2?l2->next:headA;        }        return l1;    }};


0 0