zoukankan      html  css  js  c++  java
  • 160. Intersection of Two Linked Lists

        /*
         * 160. Intersection of Two Linked Lists 
         * 11.28 by Mingyang 
         * 自己写的代码很长,但是话粗理不粗
         */
        public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
            int lenA = length(headA), lenB = length(headB);
            // move headA and headB to the same start point
            while (lenA > lenB) {
                headA = headA.next;
                lenA--;
            }
            while (lenA < lenB) {
                headB = headB.next;
                lenB--;
            }
            // find the intersection until end
            while (headA != headB) {
                headA = headA.next;
                headB = headB.next;
            }
            return headA;
        }
        private int length(ListNode node) {
            int length = 0;
            while (node != null) {
                node = node.next;
                length++;
            }
            return length;
        }
        /*
         * 那么下面是更加巧妙的方法,就是直接看两个不相等就继续走
         * 知道一个走到null以后回到另一个list的开始继续走
         * 第二次停止的时候刚好就是他们相遇的时候
         */
        public ListNode getIntersectionNode1(ListNode headA, ListNode headB) {
            //boundary check
            if(headA == null || headB == null) return null;
            ListNode a = headA;
            ListNode b = headB;
            //if a & b have different len, then we will stop the loop after second iteration
            while( a != b){
                //for the end of first iteration, we just reset the pointer to the head of another linkedlist
                a = a == null? headB : a.next;
                b = b == null? headA : b.next;    
            }
            return a;
        }
  • 相关阅读:
    14、数列
    13、Hangover
    12、Anagrams by Stack
    彩票软件7) 重构数据库accesser
    彩票软件6)观察者模式
    彩票软件5)Sqlite 数据库访问类
    彩票软件4)插叙
    彩票软件3)wpf界面布局
    彩票软件2)代码管理git
    彩票软件1)前言
  • 原文地址:https://www.cnblogs.com/zmyvszk/p/5555455.html
Copyright © 2011-2022 走看看