160. Intersection of Two Linked Lists

来源:互联网 发布:windows编程循序渐进 编辑:程序博客网 时间:2024/05/24 05:02

1.Question

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.
2.Code

/** * 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) {        if(headA && headB)        {            int m = getListLength(headA);            int n = getListLength(headB);            if(m < n) {ListNode* temp = headA; headA = headB; headB = temp;}            int s = abs(m - n);            while(s-- > 0) headA = headA->next;            while(headA)            {                if(headA == headB) return headA;                else {headA = headA->next; headB = headB->next;}            }        }        return NULL;    }    int getListLength(ListNode *node) {        int n = 0;        while(node) {n++; node = node->next;}        return n;    }};

3.Note

a. 解题思路是,如果A和B的长度相同,而且有重合部分,那么A和B的重叠部分的各自对应位置是一样的,我们只需要比较对应位置上是否重叠就行了。那么,我们只要把A和B的长度变得相同就可以了。

0 0
原创粉丝点击