leetcode 160. Intersection of Two Linked Lists

leetcode 160. Intersection of Two Linked Lists

(Easy)

Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

img

Example 1:

img

Example 2:

img

Example 3:

img

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.

  • 核心问题: 找到两个有交点的链表的交点

  • 思路一: 使用hash_map,遍历A中节点,将其加入,然后检查B中每一个节点. (不写了)

  • 思路二: 使用两个指针(Two Pointer),pA,pB,初始指向A,B的head

    每次都将指针向后推进一个元素,如果pA到达尾部,则让其指向pB head,如果pB到达尾部,则让其指向pA head

    这样两个指针相遇时则是所求的节点.

    妙啊,简单而又巧妙的想法

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        ListNode *pa = headA;
        ListNode *pb = headB;
        int check = 2;
        
        while(pa != NULL && pb != NULL)
        {
            if(pa == pb)
                return pa;
            pa = pa->next;
            if(pa == NULL && check)
            {
                pa = headB;
                check--;
            }
            
            pb = pb->next;
            if(pb == NULL && check)
            {
                pb = headA;
                check--;
            }
        }
        return NULL;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值