首页 > 其他分享 >LeetCode刷题记录.Day6

LeetCode刷题记录.Day6

时间:2022-11-04 23:34:43浏览次数:83  
标签:lenB ListNode Day6 next 链表 curB curA LeetCode 刷题

链表相交

题目链接面试题 02.07. 链表相交 - 力扣(LeetCode)

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        ListNode* curA = headA;
        ListNode* curB = headB;
        int lenA = 0, lenB = 0 ;
        while(curA != NULL){
            lenA++;
            curA = curA->next;
        }
        while(curB != NULL){
            lenB++;
            curB = curB->next;
        }
        curA = headA;
        curB = headB;
        if(lenB > lenA){
            swap(lenA, lenB);
            swap(curA, curB);
        }
        int dif;
        dif = lenA - lenB;
        while(dif--){
            curA = curA->next;
        }

        while(curA != NULL){
            if(curA == curB){
                return curA;
            }
            curA = curA->next;
            curB = curB->next;
        }
        return NULL;
    }
};

这道题解法关键是,相交的节点后面的节点也是相同的。所以两个链表的末尾一定是相等的。

所以只要使两个链表末尾对齐就可以进行查找,同样使用双指针法,快指针先移动链表长度差值的步数。还算逻辑比较清晰。

标签:lenB,ListNode,Day6,next,链表,curB,curA,LeetCode,刷题
From: https://www.cnblogs.com/tianmaster/p/16859445.html

相关文章

  • leetcode Boyer-Moore 算法
    简介如何寻求一个数组中的出现次数最多的书虽然最开始想到了这个方法但是不知道如何去表达,grep就利用了这个算法classSolution{publicintmajorityElement(int[......
  • Leetcode刷题第二周
    链表:插入快,查询慢,存储不连续分为单链表,双链表和循环链表在链表中使用虚拟头结点,可以减少增删改查中对头结点的特殊处理移除链表元素203/***Definitionforsingly......
  • LeetCode 145. 二叉树的后序遍历
    问题描述给定一个二叉树,返回它的后序遍历。示例:进阶:递归算法很简单,你可以通过迭代算法完成吗?题目代码/***Definitionforabinarytreenode.*publicclassTre......
  • leetcode-2283-easy
    CheckifNumberHasEqualDigitCountandDigitValueYouaregivena0-indexedstringnumoflengthnconsistingofdigits.Returntrueifforeveryindexi......
  • leetcode-754-medium
    ReachaNumberYouarestandingatposition0onaninfinitenumberline.Thereisadestinationatpositiontarget.YoucanmakesomenumberofmovesnumMove......
  • leetcode-657-easy
    RobotReturntoOriginThereisarobotstartingattheposition(0,0),theorigin,ona2Dplane.Givenasequenceofitsmoves,judgeifthisrobotendsup......
  • leetcode-1417-easy
    ReformatTheStringYouaregivenanalphanumericstrings.(AlphanumericstringisastringconsistingoflowercaseEnglishlettersanddigits).Youhaveto......
  • leetcode-771-easy
    JewelsandStonesYou'regivenstringsjewelsrepresentingthetypesofstonesthatarejewels,andstonesrepresentingthestonesyouhave.Eachcharacterin......
  • leetcode-1200-easy
    MinimumAbsoluteDifferenceGivenanarrayofdistinctintegersarr,findallpairsofelementswiththeminimumabsolutedifferenceofanytwoelements.Retu......
  • leetcode-1984-easy
    MinimumDifferenceBetweenHighestandLowestofKScoresYouaregivena0-indexedintegerarraynums,wherenums[i]representsthescoreoftheithstudent.......