【LeetCode】160. Intersection of Two Linked Lists

160. Intersection of Two Linked Lists

Description:
Write a program to find the node at which the intersection of two singly linked lists begins.
Difficulty:Easy
Note:
1.If the two linked lists have no intersection at all, return null.
2.The linked lists must retain their original structure after the function returns.
3.You may assume there are no cycles anywhere in the entire linked structure.
4.Your code should preferably run in O(n) time and use only O(1) memory.
Example:
在这里插入图片描述

Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
Output: Reference of the node with value = 8
Input Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,0,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
方法: 尾端对其
  • Time complexity : O ( m + n ) O\left ( m+n\right ) O(m+n)
  • Space complexity : O ( 1 ) O\left ( 1\right ) O(1)
    思路:
    计算两个链表的长度,按照尾端对其,遍历,看是否有相同元素
    另一种方法是虚链表的方法,写起来更简短。
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        int num_a = 0, num_b = 0;
        ListNode *a = headA;
        ListNode *b = headB;
        while(a) {
            num_a++;
            a = a->next;
        }
        while(b) {
            num_b++;
            b = b->next;
        }
        if(num_a==0 || num_b==0) return NULL;
        if(num_a > num_b) {
            int dist = num_a - num_b;
            while(dist > 0){
                headA = headA->next;
                dist--;
            }
        }
        else{
            int dist = num_b - num_a;
            while(dist > 0){
                headB = headB->next;
                dist--;
            }
        }
        while(headA&&headB){
            if(headA == headB)
                return headA;
            headA = headA->next;
            headB = headB->next;
        }
        return NULL;
        
    }
};

虚链表

ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
    ListNode *cur1 = headA, *cur2 = headB;
    while(cur1 != cur2){
        cur1 = cur1?cur1->next:headB;
        cur2 = cur2?cur2->next:headA;
    }
    return cur1;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值