zoukankan      html  css  js  c++  java
  • 牛客(36)两个链表的第一个公共结点

    //    题目描述
    //    输入两个链表,找出它们的第一个公共结点。
        public static class ListNode {
            int val;
            ListNode next = null;
    
            ListNode(int val) {
                this.val = val;
            }
        }
    
        public static ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
            if (pHead1 == null||pHead2 == null) {
                return null;
            }
            int count1=0;
            ListNode p1 = pHead1;
            while(p1!=null){
                count1++;
                p1 = p1.next;
            }
            int count2=0;
            ListNode p2 = pHead2;
    
            while(p2!=null){
                count2++;
                p2 = p2.next;
            }
            if (count1>count2){
                while (count1>count2){
                    pHead1 = pHead1.next;
                    count1--;
                }
            }
            if (count1<count2){
                while (count1<count2){
                    pHead2 = pHead2.next;
                    count2--;
                }
            }
            while (pHead1!=pHead2){
                pHead2 = pHead2.next;
                pHead1 = pHead1.next;
            }
            return pHead2;
    
        }
  • 相关阅读:
    我的期末可以加分项
    冲刺
    公司授课管理系统
    挑战赛题终于完成
    Java web 学习
    Java web 学习
    Javaweb 学习
    Base64加密
    选课系统
    Educational Codeforces Round 62题解
  • 原文地址:https://www.cnblogs.com/kaibing/p/9045717.html
Copyright © 2011-2022 走看看