【LeetCode & 剑指offer刷题】链表题5:52 两个链表的第一个公共结点(Intersection of Two Linked Lists)

【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

52 两个链表的第一个公共结点

题目描述

输入两个链表,找出它们的第一个公共结点。
 
/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
#include <cmath>
class Solution
{
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2)
    {
        //求两链表的长度
        int len1 = findListLength(pHead1);
        int len2 = findListLength(pHead2);
       
        ListNode* plong = pHead1, *pshort = pHead2;
        if(len1 < len2)
        {
            pshort = pHead1;
            plong = pHead2;
        }
        for(int i = 1; i <= abs(len1-len2); i++) plong = plong->next; //较长的链表多走几步
       
        //同时步进,直到遇到相同结点或者均遇到尾结点
        while(plong != pshort)
        {
            plong = plong->next;
            pshort = pshort->next;
        }
       
        return plong;
    }
 
private:
    int findListLength(ListNode* p)
    {
        int n = 0;
        while(p != nullptr)
        {
            p = p->next;
            n++;
        }
        return n;
    }
};
 
 
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.
Credits:
Special thanks to @stellari for adding this problem and creating all test cases.

C++
 
//问题:求两链表的交汇点
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/*
方法:双指针法
(1) 如果有交汇点,p1扫描A,p2扫描B,扫描到结尾后,p1重定向到headB,p2重定向到headA,之后一定会在交汇点处相遇
因为交汇点之后都是路径相同的,交汇点之前的路径差可以由互换的两次扫描中抵消
(2) 如果没有交汇点,p1最后会到b末尾,p2会到a末尾,p1=p2=null,退出程序
O(m+n),O(1)
*/
class Solution
{
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
    {
        ListNode *p1 = headA;
        ListNode *p2 = headB;
        if(p1 == NULL || p2 == NULL) return NULL;
        
       
        while(p1 && p2 && p1!=p2) //只要不为空,进行扫描(注意,加上p1!=p2的判断,可能两链表长度为1,且相交,不加的话会返回null)
        {
            p1 = p1->next;
            p2 = p2->next;
            if(p1 == p2) return p1//p1,p2同时为nullptr或者指向交汇点
            if(p1 == NULL) p1 = headB; //重定向到另一个链表首结点 
            if(p2 == NULL) p2 = headA;
        }
        return p1;
    }
};
 

 

posted @ 2019-01-05 16:53  wikiwen  阅读(130)  评论(0编辑  收藏  举报