zoukankan      html  css  js  c++  java
  • 剑指 Offer 52. 两个链表的第一个公共节点

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
            int nLength1 = GetListLen(headA);
            int nLength2 = GetListLen(headB);
            int nLengthDif = nLength1 - nLength2;
    
            ListNode pListHeadLong = headA;
            ListNode pListHeadShort =headB;
    
            if(nLength2 > nLength1){
                pListHeadLong = headB ;
                pListHeadShort = headA ;
                nLengthDif = nLength2 - nLength1;
            }
            //长的先走
            for(int i=0;i<nLengthDif;i++){
                pListHeadLong = pListHeadLong.next;
            }
            while((pListHeadLong!=null)&& (pListHeadShort!=null)&& (pListHeadShort != pListHeadLong)){
                pListHeadLong = pListHeadLong.next;
                pListHeadShort = pListHeadShort.next;
            }
            //得到公共节点
            ListNode pListHeadCommonNode = pListHeadLong;
            return pListHeadCommonNode;
        }
    
    
        //计算链表的长度
        int GetListLen(ListNode pHead){
            int nlen = 0;
            ListNode pNode = pHead;
            while(pNode!= null){
                nlen++;
                pNode = pNode.next;
            }
            return nlen;
        }
    }

    剑指offer上 大神 腐烂的橘子 的题解,感动了众多刷题狗,没想到刷题也这么浪漫

  • 相关阅读:
    Eclipse中项目去除Js验证
    Web安全扫描工具
    Oracle-定时任务
    About_Return
    About_php_封装函数
    About_PHP_函数
    About_PHP_验证码的生成
    About_PHP_文件的上传
    About_MySQL Select--来自copy_03
    About_AJAX_03
  • 原文地址:https://www.cnblogs.com/peanut-zh/p/14146686.html
Copyright © 2011-2022 走看看