博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode学习笔记(160. 相交链表)
阅读量:4050 次
发布时间:2019-05-25

本文共 2175 字,大约阅读时间需要 7 分钟。

在这里插入图片描述

三种解法实现,第三种有点巧妙,值得考虑:

暴力遍历:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {
public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(headA==nullptr||headB==nullptr) return nullptr; ListNode *curA=headA,*curB=headB; while(curA!=nullptr){
while(curB!=nullptr){
if(curB==curA) return curA; curB = curB->next; } curA=curA->next; curB = headB; } return nullptr; }};

Hash表:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {
public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(headA==nullptr||headB==nullptr) return nullptr; ListNode *curA=headA,*curB=headB; unordered_set
data; while(curA!=nullptr){
data.insert(curA); curA=curA->next; } while(curB!=nullptr){
if(data.find(curB)!=data.end()) return curB; curB = curB->next; } return nullptr; }};

双指针:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {
public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(headA==nullptr||headB==nullptr) return nullptr; ListNode *curA=headA,*curB=headB; bool signA=true,signB=true; while(curA!=nullptr||curB!=nullptr){
if(curA==curB&&curA!=nullptr) return curA; curA = curA->next; curB = curB->next; if(curA==nullptr&&signA){
curA=headB; signA=false; } if(curB==nullptr&&signB){
curB=headA; signB=false; } } return nullptr; }};

转载地址:http://uvyci.baihongyu.com/

你可能感兴趣的文章
Idea导入的工程看不到src等代码
查看>>
技术栈
查看>>
Jenkins中shell-script执行报错sh: line 2: npm: command not found
查看>>
8.X版本的node打包时,gulp命令报错 require.extensions.hasownproperty
查看>>
Jenkins 启动命令
查看>>
Maven项目版本继承 – 我必须指定父版本?
查看>>
通过C++反射实现C++与任意脚本(lua、js等)的交互(二)
查看>>
利用清华镜像站解决pip超时问题
查看>>
微信小程序开发全线记录
查看>>
CCF 分蛋糕
查看>>
解决python2.7中UnicodeEncodeError
查看>>
小谈python 输出
查看>>
Django objects.all()、objects.get()与objects.filter()之间的区别介绍
查看>>
python:如何将excel文件转化成CSV格式
查看>>
机器学习实战之决策树(一)
查看>>
机器学习实战之决策树二
查看>>
[LeetCode By Python]7 Reverse Integer
查看>>
[leetCode By Python] 14. Longest Common Prefix
查看>>
[LeetCode By Python]121. Best Time to Buy and Sell Stock
查看>>
[LeetCode By Python]122. Best Time to Buy and Sell Stock II
查看>>