[LeetCode]Intersection of Two Linked Lists

思路:
条件比较严:
1,不破坏数据结构;
2,时间复杂度O(n), 空间复杂度O(1)
3,假设没有环路;
4,没有交点,返回null

反过来想,从链表的结尾开始,向链表header开始数,对同一个index对应的node,链表A和B的address在intersection之前都是相等的,在intersection之后开始不同。
但题目所述链表非双向list,我们必须list的header开始,向后找intersection。所以,我们必须找到一个node,在这个node之后,链表A和B是等长的
1,先决条件:计算链表A和B的长度,初始化链表A和B的游标CurA 和CurB,较长的链表的游标Cursor移动 | A.length - B.length|个单位
2,不变式:比较CurA 和CurB的address
3,结束条件:address相同,或者同时为null
4,临界条件:链表A和B不为null


//编译错误
1,调用结构体指针的value,要用 “ -> “
// Runtime Error;

1,没有初始化 CurA 和CurB 


/**
 * 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;

        int lenA = 0;
        int lenB = 0;
        ListNode *p = headA;
        while (p != NULL){
            lenA ++;
            p = p->next;
        }

        p = headB;
        while (p != NULL){
            lenB ++;
            p = p->next;
        }

        ListNode *curA = headA;
        ListNode *curB = headB;
        if (lenA > lenB){
            int i = 0;
            while (i < lenA - lenB){
                curA = curA->next;
                i ++;
            }

        }else if (lenB > lenA){
            int i = 0;
            while (i < lenB - lenA){
                curB = curB->next;
                i ++;
            }
        }
        while (curA != curB){
            curA = curA->next;
            curB = curB->next;
        }
        return curA;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值