160. Intersection of Two Linked Lists

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
这里写图片描述
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,题目思路
个人的思路是,先分别找出两个链表的长度,然后利用二者的长度之差,将长的链表“减去”对应的长度,如果两个链表真的有交集的话, 则此时二者在交集处的位置一定是一样的。
另外一种比较有意思的方法,则是利用了两次迭代。第一次迭代,去除两个链表之间的长度差异;第二次迭代,则尝试找到两个链表中节点相等的点。

3,程序源码
方法1:

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        if(headA == NULL || headB == NULL)  return NULL;

        int lenA = GetListLenHelper(headA), lenB = GetListLenHelper(headB);
        int skew = 0;
        if(lenA>lenB)
        {
            skew = lenA - lenB;
            while(skew>0){
                headA = headA->next;
                skew--;
            }
        }
        else{
            skew = lenB - lenA;
            while(skew>0){
                headB = headB->next;
                skew--;
            }
        }

        while(headA!=NULL||headB!=NULL)
        {
            if(headA->val == headB->val)
                return headA;
            else{
                headA = headA->next;
                headB = headB->next;
            }
        }
        return NULL;
    }
public:
    int GetListLenHelper(ListNode *head){
        int len = 0;
        while(head!= NULL){
            head = head->next;
            len++;
        }
        return len;
    }
};

方法2:

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        if(headA == NULL || headB == NULL)  return NULL;

        ListNode *a = headA;
        ListNode *b = headB;

        while(a!=b){
            a = a == NULL?headB : a->next;//当找到表A的尾部时,a就开始指向表B
            b = b == NULL?headA : b->next;//b也一样,这样一定有一个先指向另一个表,也就使得二者的长度之差得到了补偿
            //画一个链表图就非常的直观了
            //第二轮迭代时,a和b所要遍历的剩余节点的数量都是一样的
            //因此即使没有交集,当a遍历到结尾的NULL时,返回值也是正确的
        }
        return a;
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值