标签: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:
null
.含义:两个列表有交集,求出他们的交集开始点
方法一:
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