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       }
  • 相关阅读:
    OC面向对象—继承
    OC面向对象—封装
    OC内存管理
    OC方法和文件编译
    OC语言基础知识
    节点操作-2
    留言 节点操作案例
    js 下拉菜单案例
    节点操作
    tab栏切换效果
  • 原文地址:https://www.cnblogs.com/ordili/p/4970021.html
Copyright © 2011-2022 走看看