LeetCode-160. Intersection of Two Linked Lists

来源:互联网 发布:三国志9高难度优化伴侣 编辑:程序博客网 时间:2024/06/05 04:25

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.
剑指offer中原题,更详细的思考过程和解答参考它。

思路:

1、从表尾往前看,可以看出链表在相交以后的节点值和节点数目都相同,不同的地方在于未相交前时两链表的节点数目,所以我们可以遍历两个链表记录下每个链表的长度。

2、用两个指针分别指向两链表的表头,节点数目多的链表指针先走n歩后,n为两链表的节点数目之差,节点数目少的链表再走

3、在这个过程中,只要找到相同的节点就找到了交汇处,如果直到表尾都没有找到则说明两链表没有交汇,返回null。

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {        int lengthOfListA=getLengthOfList(headA);        int lengthOfListB=getLengthOfList(headB);        ListNode* pA=headA;        ListNode* pB=headB;        if(lengthOfListA>lengthOfListB)        {            int plusLength=lengthOfListA-lengthOfListB;            for(int i=0;i<plusLength;++i)            {                pA=pA->next;            }        }        else if(lengthOfListA<lengthOfListB)        {            int plusLength=lengthOfListB-lengthOfListA;            for(int i=0;i<plusLength;++i)            {                pB=pB->next;            }        }        while(pA&&pB)        {            if(pA->val==pB->val)                return pA;            pA=pA->next;            pB=pB->next;        }        return NULL;    }    int getLengthOfList(ListNode* head)    {        int length=0;        while(head!=nullptr)        {            length++;            head=head->next;        }        return length;    }};



原创粉丝点击