LeetCode -- Intersection of Two Linked Lists

来源:互联网 发布:云计算未来带来的好处 编辑:程序博客网 时间:2024/06/10 01:07
题目描述:
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.


找到链表相交的节点,如果不相交返回null。


思路:
如果链表相交,设焦点为p,那么p之后的节点在链表A和链表B中必然是相同的,基于这一点:
1. 计算出链表A的长度lenA
2. 计算出链表B的长度lenB
3. 将长度长的那个链表的指针移动lenA-lenB(链表A长)或lenB-lenA(链表B长)位。
4. 同时向后移动pA(链表A指针)和pB(链表B指针),比较它们是否相等,相同则返回这个节点。
5. 直到最后都没有找到相等,则视为不相交,返回null。




实现代码:



/** * Definition for singly-linked list. * public class ListNode { *     public int val; *     public ListNode next; *     public ListNode(int x) { val = x; } * } */public class Solution {    public ListNode GetIntersectionNode(ListNode headA, ListNode headB)     {        var lenA = Len(headA);    var lenB = Len(headB);        if(lenA == 0 || lenB == 0){    return null;    }        var pA = headA;    var pB = headB;    if(lenA > lenB){    var steps = lenA-lenB;    for(var i = 0;i < steps; i++){    pA = pA.next;    }    }    else if(lenA < lenB){    var steps = lenB-lenA;    for(var i = 0;i < steps; i++){    pB = pB.next;    }    }        while(pA != null){    if(ReferenceEquals(pA , pB)){    return pA;    }    pA = pA.next;    pB = pB.next;    }        return null;    }private int Len(ListNode node){var p = node;var len = 0;while(p != null){len ++;p = p.next;}return len;}}


1 0
原创粉丝点击