Leetcdoe-Day13-代码随想录-链表-面试题目0207-142

面试题 02.07. 链表相交

题目链接
题解:链表相交,就是指指向节点的指针相同,即cura=curb。由于两个链表如果在末尾可能出现相交,那可以将两个链表末尾对齐,然后从短链头开始往后搜索,即cura/curb移动到同时开始的位置。那么就需要先计算出两个链表的长度,然后判断大小,通过差值进行迭代。其中需要注意的是,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) {
        ListNode* cura=headA;
        ListNode* curb=headB;
        int lengtha=0;
        int lengthb=0;
        while(cura!=NULL){
            cura=cura->next;
            lengtha++;
        }
        while(curb!=NULL){
            curb=curb->next;
            lengthb++;
        }
        cura=headA;
        curb=headB;
        if(lengtha>lengthb){
            int cha=lengtha-lengthb;
            while(cha>0){
                cura=cura->next;
                cha--;
            }
        }else if(lengtha<lengthb){
            int cha=lengthb-lengtha;
            while(cha>0){
                curb=curb->next;
                cha--;
            }
        }
        while(cura!=curb&&cura!=NULL&&curb!=NULL){
            cura=cura->next;
            curb=curb->next;
        }
        return cura;
    }
};

在这里插入图片描述

142.环形链表II

题目链接
题解:分别定义 fast 和 slow 指针,从头结点出发,fast指针每次移动两个节点,slow指针每次移动一个节点,如果 fast 和 slow指针在途中相遇 ,说明这个链表有环。从头结点出发一个指针,从相遇节点 也出发一个指针,这两个指针每次只走一个节点, 那么当这两个指针相遇的时候就是 环形入口的节点。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode* fast = head;
        ListNode* slow = head;
        while(fast != NULL && fast->next != NULL) {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast) {
                ListNode* index1 = fast;
                ListNode* index2 = head;
                while (index1 != index2) {
                    index1 = index1->next;
                    index2 = index2->next;
                }
                return index2; // 返回环的入口
            }
        }
        return NULL;
    }
};

在这里插入图片描述

  • 7
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值