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

    1. Title

    Intersection of Two Linked Lists

    2. Http address

    https://leetcode.com/problems/intersection-of-two-linked-lists/

    3. The question

    Write a program to find the node at which the intersection of two singly linked lists begins.

    For example, the following two linked lists:

    A:          a1 → a2
                       ↘
                         c1 → c2 → c3
                       ↗            
    B:     b1 → b2 → b3
    

    begin to intersect at node c1.

    4. My code (AC)

      

     1     // Accepted
     2       public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
     3   
     4           if( headA == null || headB == null)
     5               return null;
     6           if( headA == headB)
     7               return headA;
     8           
     9           int lenA,lenB,distance;
    10           ListNode p,q;
    11           lenA = 0;
    12           p = headA;
    13           while( p != null)
    14           {
    15               lenA++;
    16               p = p.next;
    17           }
    18           
    19           lenB = 0;
    20           q = headB;
    21           while( q != null)
    22           {
    23               lenB++;
    24               q = q.next;
    25           }
    26           
    27           if( lenA >=lenB)
    28           {
    29               distance = lenA - lenB;
    30               p = headA;
    31               for(int i = 1; i <= distance; i++)
    32               {
    33                   p = p.next;
    34               }
    35               q = headB;
    36               while( p != null && q != null && p != q)
    37               {
    38                   p = p.next;
    39                   q = q.next;
    40               }
    41               return p;
    42           }else{
    43               distance = lenB - lenA;
    44               p = headB;
    45               for(int i = 1; i <= distance; i++)
    46               {
    47                   p = p.next;
    48               }
    49               q = headA;
    50               while( p != null && q != null && p != q)
    51               {
    52                   p = p.next;
    53                   q = q.next;
    54               }
    55               return p;
    56           }
    57           
    58       }
  • 相关阅读:
    工作笔记之20170223:①关于Html5的placeholder属性,②以及input的outline:none的样式问题
    工作笔记之:如何在eclipse安装CVS插件?找了很久的,自己总结一下
    ajax后台请求两种方法(js和jQuery)
    22
    21
    20
    19
    18
    17
    16
  • 原文地址:https://www.cnblogs.com/ordili/p/4970021.html
Copyright © 2011-2022 走看看