https://leetcode.com/problems/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:
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 遍历linkedList,得到length和tail;
2 Compare tails(reference 对比,不是value对比),如果不同,直接返回;没有intersection;
3 指针指向每个linked List的开始;
4 较长的linked List,移动两个linked list的长度差;
5 遍历每个linked list, 直到指针相同;
C#代码
ListNode FindIntersection(ListNode list1,ListNode list2)
{
if (list1 == null || list2 == null) return null;
//获取tail和size
Result result1 = GetTailAndSize(list1);
Result result2 = GetTailAndSize(list2);
//如果tail reference不同,就没有intersection
if (result1.tail != result2.tail)
return null;
//定位2个指针到linked list的头部
ListNode shorter = result1.size < result2.size ? list1 : list2;
ListNode longer = result1.size < result2.size ? list2 : list1;
//长linked list的指针向前移动长度差
longer = GetKthNode(longer, Math.Abs(result1.size-result2.size));
//移动两根指针,直到collision
while (shorter != longer)
{
shorter = shorter.next;
longer = longer.next;
}
//任意返回一个
return longer;
}
Result GetTailAndSize(ListNode list)
{
if (list == null)
return null;
int size = 1;
ListNode current = list;
while (current.next != null)
{
size++;
current = current.next;
}
return new Result(current,size);
}
ListNode GetKthNode(ListNode head,int k)
{
ListNode current = head;
while ( k>0 && current != null )
{
current = current.next;
k--;
}
return current;
}
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int x) { val = x; }
}
public class Result
{
public ListNode tail;
public int size;
public Result(ListNode _tail,int _size)
{
tail = _tail;
size = _size;
}
}