leetcode之判断两链表首次交汇节点

来源:互联网 发布:谷歌seo公司 编辑:程序博客网 时间:2024/05/14 04:47

题目:

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.

思路:先遍历左链表,再遍历右链表,遍历的时候分别计数,遍历完成后,如果最后一个节点不同,则没有交点,否则,可判断有交点,在有交点的情况下,看两条链表的便利次数M,N,然后再重新遍历,不过这次遍历先让长的那条链表先走|M-N|步,然后两边同时向前,每一步判断节点地址是否相等,第一次相等的即为首个交汇点。逻辑就是这样,但是这里有一些边界条件必须注意,否则,有了这个思路一样会出错。



代码

/** * 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) {        ListNode* p1=headA;        ListNode* p2=headB;        if(p1==NULL||p2==NULL)        {            return NULL;        }        if(p1==p2)        {            return p1;        }        int i=1;        int j=1;        while(p1->next!=NULL)        {            p1=p1->next;            i++;        }        while(p2->next!=NULL)        {            p2=p2->next;            j++;        }        //no intersection, last node not the same        if(p1!=p2)        {            return NULL;        }        //else        p1=headA;        p2=headB;        if(i>j)        {            int diff=i-j;            while(diff>0)            {                p1=p1->next;                diff--;            }        }else if(j>i)        {            int diff=j-i;            while(diff>0)            {                p2=p2->next;                diff--;            }        }        if(p1==p2)        {            return p1;        }        while(p1->next!=p2->next)        {            p1=p1->next;            p2=p2->next;        }        return p1->next;    }};

0 0
原创粉丝点击