leetcode160. Intersection of Two Linked Lists

CSDN博客作为leetcode刷题笔记,以后有机会会补上机器学习的内容和之前kaggle比赛的代码。

这道题有两种解法。第一种是算出两条链表的长度的差值。用比较长的链表移位差值大小,就可以一一比较了。

c++,解法一:

/**
 * 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 lengthA = 0,lengthB =0;
        for(ListNode *i = headA;i!=NULL;i = i->next)
            lengthA += 1;
        for(ListNode *i = headB;i!=NULL;i = i->next)
            lengthB += 1;
        if (lengthA > lengthB){
            int step = lengthA - lengthB;
            for (int i = 0; i < step; i++){
                headA = headA -> next;
            }
        }
        else if(lengthA < lengthB){
            int step = lengthB - lengthA;
            for (int i = 0; i <step; i++){
                headB = headB -> next;
            }
        }
        while (headA!=NULL && headB!=NULL){
            if(headA == headB){
                return headA;
            }
            headA = headA -> next;
            headB = headB -> next;
        }
        return NULL;
    }
};

第二种做法要更巧妙一些,便利两个列表,要是到头就从另一个列表的head开始,所以当两个列表走完相同的路程后,要么不相交,到达各自末尾,return NULL。要么相交,就是相遇的节点,输出即可。

c++,解法二:

/**
 * 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;
        ListNode *a = headA, *b = headB;
        while(true){
            if (a==b)
                return a;
            else if (a->next ==NULL && b -> next == NULL)
                return NULL;
            if (a->next == NULL)
                a = headB;
            else
                a = a -> next;
            if (b->next == NULL)
                b = headA;
            else 
                b = b -> next;
        }
    }
};

两种做法的运行时间是一样的,但是第二种代码要短一些。

第三种做法,c++;

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        if (headA == NULL || headB == NULL)
            return NULL;
        ListNode *a = headA, *b = headB;
        while(true){
            if (a==b) {
                if (a == NULL) return NULL;
                else return a;
            }
            a = a==NULL ? headB:a->next;
            b = b==NULL ? headA:b->next;
        }   
    }
};

思路和第二种是一样的,优化了代码,但是跑的时间变慢,28ms。前两种是24ms。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值