[LeetCode]160. Intersection of Two Linked Lists

本文介绍了解决LeetCode 160题“两个链表的交点”的一种高效算法,通过双指针技巧避免了额外的空间消耗,实现了O(1)的空间复杂度。文章提供了完整的C++代码实现,并附带示例说明。

[LeetCode]160. Intersection of Two Linked Lists

题目描述

这里写图片描述

思路

本来打算使用翻转链表来做,但是由于链表的结构,和空间复杂度要求,没有成功,之后参考了答案的思路

代码

#include <iostream>

using namespace std;

struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* cur = NULL;
        while (head) {
            ListNode* next = head->next;
            head->next = cur;
            cur = head;
            head = next;
        }
        return cur;
    }

    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;
    }

    void printList(ListNode* head) {
        while (head) {
            cout << head->val << " ";
            head = head->next;
        }
        cout << endl;
    }
};

int main() {
    ListNode *l1 = new ListNode(1);
    ListNode *l2 = new ListNode(2);
    ListNode *l3 = new ListNode(3);
    ListNode *l4 = new ListNode(4);
    ListNode *l5 = new ListNode(5);
    ListNode *l6 = new ListNode(6);

    l1->next = l2;
    l2->next = l3;
    l3->next = l4;

    //l6->next = l3;

    Solution s;

    ListNode* res = s.getIntersectionNode(l6, l5);
    s.printList(res);

    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值