链表链表相交

leetcode:链表相交

Method

判断链表相交否,先看两个链表的长度,使得长链表移动长度之差绝对值的长度,移动后的两个新链表长度一样,在判断两个节点是否地址相同

代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* MovementNode(ListNode* node, int n){
        while(n--){
            node = node->next;
        }
        return node;
    }
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        int lenA = 0;
        int lenB = 0;
        ListNode* node = headA;
        while (node) {
            lenA++;
            node = node->next;
        }
        node = headB;
        while (node) {
            lenB++;
            node = node->next;
        }
        if (lenA > lenB) {//移动A
           headA = MovementNode(headA, lenA - lenB);
        } else{
            headB = MovementNode(headB,lenB - lenA);
        }
        bool is = false;//判断师傅相同
        while (headA && headB) {
            if (headA == headB) {
                is = 1;
                break;
            }
            headA = headA->next;
            headB = headB->next;
        }
        return is ? headA : nullptr;
    }
};


















posted @ 2023-02-25 10:28  壹剑霜寒十四州  阅读(8)  评论(0编辑  收藏  举报