首页 > 其他 > 详细

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

时间:2019-05-14 10:08:55      阅读:125      评论:0      收藏:0      [点我收藏+]

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 }

 

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

原文:https://www.cnblogs.com/liuliu5151/p/10860159.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!