链表的公共节点

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_28350997/article/details/83214334

求链表的公共节点
160. Intersection of Two Linked Lists

先求出链表的长度, 让两个链表的长度一样的情况,然后逐步推进, 不等的话一直走下去, 直到走到相同的地方情况下

如果没有公共公共节点的话,两个节点共同走到空节点,然后直接返回即可

/**
 * 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==nullptr|| headB==nullptr) return NULL;
         int m = getlen(headA);
         int n = getlen(headB);
         while(m-n>0){
             headA  = headA->next;
             --m;
         }
         while(n-m>0){
              headB = headB->next;
                --n;
         }
         
         while(headA!=headB){
             headA = headA->next;
             headB = headB->next;
         }
         return headA;
    }
    int getlen(ListNode *headA){
        int len=0;
        while(headA){
            ++len;
            headA = headA->next;
        }
        return len;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_28350997/article/details/83214334