博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
牛客网 | 高频面试题 | 判断链表中是否有环
阅读量:4141 次
发布时间:2019-05-25

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

文章目录

题目

题目描述判断给定的链表中是否有环。如果有环则返回true,否则返回false。你能给出空间复杂度的解法么?

题解

快慢指针

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {
public: bool hasCycle(ListNode *head) {
if(head==nullptr||head->next==nullptr)return false; ListNode *slow=head,*fast=head->next; //链表多长? while(slow!=fast){
if(fast==nullptr||slow==nullptr||fast->next==nullptr)return false; slow=slow->next; fast=fast->next->next; } return true; }};

哈希表

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {
public: bool hasCycle(ListNode *head) {
set
hash_map; ListNode *p=head; while(p!=nullptr){
if(hash_map.count(p)){
return true; } hash_map.insert(p); p=p->next; } return false; }};

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

你可能感兴趣的文章
NG深度学习第二门课作业1-1 深度学习的实践
查看>>
Ubuntu下安装Qt
查看>>
Qt札记
查看>>
我的vimrc和gvimrc配置
查看>>
hdu 4280
查看>>
禁止使用类的copy构造函数和赋值操作符
查看>>
C++学习路线
查看>>
私有构造函数
查看>>
组队总结
查看>>
TitledBorder 设置JPanel边框
查看>>
DBCP——开源组件 的使用
查看>>
抓包工具
查看>>
海量数据相似度计算之simhash和海明距离
查看>>
DeepLearning tutorial(5)CNN卷积神经网络应用于人脸识别(详细流程+代码实现)
查看>>
DeepLearning tutorial(6)易用的深度学习框架Keras简介
查看>>
DeepLearning tutorial(7)深度学习框架Keras的使用-进阶
查看>>
流形学习-高维数据的降维与可视化
查看>>
Python-OpenCV人脸检测(代码)
查看>>
python+opencv之视频人脸识别
查看>>
人脸识别(OpenCV+Python)
查看>>