LeetCode 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 ==  NULL || headB == NULL){
            return NULL;
        }
        ListNode *tempA = headA;
        int lenA = 0;
        ListNode *tempB = headB;
        int lenB = 0;
        while(tempA != NULL){
            tempA = tempA->next;
            lenA++;
        }
        while(tempB != NULL){
            tempB = tempB->next;
            lenB++;
        }
        int num = lenA - lenB;
        tempA = headA;
        tempB = headB;
        if(num > 0) {
            while(num){
                tempA = tempA->next;
                num--;
            }
        } else {
            num = -num;
            while(num){
                tempB = tempB->next;
                num--;
            }
        }
        while(tempA != tempB){
            tempA = tempA->next;
            tempB = tempB->next;
        }
        return tempA;
    }
};

思路二:

/**
 * 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 *tempA = headA;
        ListNode *tempB = headB;
        while(tempA != tempB){
            if(tempA == NULL) {
                tempA = headB;
            } else {
                tempA = tempA->next;
            }
            if(tempB == NULL) {
                tempB = headA;
            } else {
                tempB = tempB->next;
            }
        }
        return tempA;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值