第一道是剑指offer里边的37题,O(m+n)的思路是先计算两个链表的长度len1,len2,然后长链表先走|len1-len2|(绝对值)步,然后从两个链表开始遍历,比较两边的结点点是否相等,代码如下: public class Solution {     public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {    int len1=lenOfList(pHead1);         int len2=lenOfList(pHead2);                 ListNode current1=pHead1;         ListNode current2=pHead2;         int step=0;         if(len1>len2){             step=len1-len2;             while(step>0){                 current1=current1.next;                 step--;             }         }else{             step=len2-len1;             while(step>0){                 current2=current2.next;                 step--;             }         }                         while(current1!=current2){             current1=current1.next;             current2=current2.next;         }                 return current1;     }         public int lenOfList(ListNode pHead){         ListNode current=pHead;         int count=0;         while(current!=null){             count++;             current=current.next;         }                 return count;     } }
点赞 1

相关推荐

天门一键开:她的意思是问你有没有论文吧
点赞 评论 收藏
分享
__Offer__:认识的室友啥也不回细节,线下面联想大模型一次通关我给我干不回了
点赞 评论 收藏
分享
牛客网
牛客网在线编程
牛客网题解
牛客企业服务