码迷,mamicode.com
首页 > 其他好文 > 详细

160. Intersection of Two Linked Lists

时间:2017-10-25 15:17:16      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:rabl   note   sts   lis   second   memory   code   style   iter   

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.

Notes:

    • If the two linked lists have no intersection at all, return null.
    • The linked lists must retain their original structure after the function returns.
    • You may assume there are no cycles anywhere in the entire linked structure.
    • Your code should preferably run in O(n) time and use only O(1) memory.

含义:两个列表有交集,求出他们的交集开始点

方法一:

 1     public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
 2         ListNode a = headA;
 3         ListNode b = headB;
 4         //if a & b have different len, then we will stop the loop after second iteration
 5         while( a != b){
 6             //for the end of first iteration, we just reset the pointer to the head of another linkedlist
 7             a = a == null? headB : a.next;
 8             b = b == null? headA : b.next;
 9         }
10         return a; //如果a不等于null,代表找到了交集的开始点  如果a等于null,说明两个列表没有交集
11 }

方法二:

 1 private int getListLength(ListNode head) {
 2         int length = 0;
 3         while (head != null) {
 4             length++;
 5             head = head.next;
 6         }
 7         return length;
 8 }
 9 
10 public class Solution {
11     public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
12         int lengthA = getListLength(headA);
13         int lengthB = getListLength(headB);
14         while (lengthA > lengthB) {
15             lengthA--;
16             headA = headA.next;
17         }
18         while (lengthB > lengthA) {
19             lengthB--;
20             headB = headB.next;
21         }
22         while (headA != headB) {
23             headA = headA.next;
24             headB = headB.next;
25         }
26         return headA; //如果headA不等于null,代表找到了交集的开始点  如果headA等于null,说明两个列表没有交集
27 }

 

160. Intersection of Two Linked Lists

标签:rabl   note   sts   lis   second   memory   code   style   iter   

原文地址:http://www.cnblogs.com/wzj4858/p/7728702.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!