• [leetcode]160. Intersection of Two Linked Lists两链表交点


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

    For example, the following two linked lists:

    begin to intersect at node c1.

    Example 1:

    Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
    Output: Reference of the node with value = 8
    Input Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). 
    From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,0,1,8,4,5].
    There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.

    题意: 

    描述:给定两个链表,可能相交于某节点。请找出此节点。

    Solution1:  

    1.  Find the lengths of two lists

    2. Ask longer length list to move diff steps (for loop)

    3. Ask two lists to move steps until headA == headB(while loop)

    code

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) {
     7  *         val = x;
     8  *         next = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13     public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    14         if (headA == null || headB == null) return null;
    15         int lenA = getLength(headA);
    16         int lenB = getLength(headB);
    17         if (lenA > lenB) {
    18             for (int i = 0; i < lenA - lenB; ++i) {
    19                 headA = headA.next;
    20             }
    21         } else {
    22             for (int i = 0; i < lenB - lenA; ++i) {
    23                 headB = headB.next;
    24             }
    25         }
    26         while (headA != null && headB != null && headA != headB) {
    27             headA = headA.next;
    28             headB = headB.next;
    29         }
    30         return (headA != null && headB != null) ? headB : null;
    31     }
    32 
    33     public int getLength(ListNode head) {
    34         int count = 0;
    35         while (head != null) {
    36             ++count;
    37             head = head.next;
    38         }
    39         return count;
    40     }
    41 }
  • 相关阅读:
    VXDIAG VX Manager V1.8.0.0814更新指南
    Java Stream 源码分析
    RESTful接口实战
    Java面经
    开发中遇到的问题:push to origin/master was rejected错误解决方案
    开发遇到的问题:springboot问题:Unable to find main class
    java封神之路-stream流-进阶
    Java封神之路-stream流-入门
    Java封神之路-设计模式-工厂模式
    JAVA封神之路-设计模式-单例模式
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10860159.html
Copyright © 2020-2023  润新知