博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
算法-链表-判断链表是否有环
阅读量:3960 次
发布时间:2019-05-24

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

在这里插入图片描述

方法一 哈希表

将每次遍历的节点加入set集合 如果有重复的节点就不可以加入

/** * Definition for singly-linked list. * class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null) {
return false; } //创建一个set集合 Set
set = new HashSet<>(); //遍历所有节点 将节点加入集合 加入失败说明有环 while(head != null) {
if(!set.add(head)) {
return true; } head = head.next; } return false; }}

方法二 快慢指针

/** * Definition for singly-linked list. * class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {
public boolean hasCycle(ListNode head) {
//没有节点 或者只有一个节点是不可能成环的 if(head == null || head.next == null) {
return false; } //采用快慢指针的方式解题,如果有环,快慢指针会再次相遇 //慢指针一次走一步 快指针一次走两步 //首先创建两个指针 这里不能让快慢指针从同一位置开始 不会进入while循环 ListNode fast = head.next; ListNode slow = head; //遍历链表 如果两者没相遇就一直遍历 没到链表的末尾就一直遍历 while(slow != fast) {
//在遍历的过程中 如果遍历到了末尾就表示没有环 fast跑的快 只需要对fast进行判断 if(fast == null || fast.next == null || fast.next.next == null) {
return false; } slow = slow.next; fast = fast.next.next; } //退出while循环说明相遇 就有环 return true; }}
/** * Definition for singly-linked list. * class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {
public boolean hasCycle(ListNode head) {
//没有节点 或者只有一个节点是不可能成环的 if(head == null || head.next == null) {
return false; } //采用快慢指针的方式解题,如果有环,快慢指针会再次相遇 //慢指针一次走一步 快指针一次走两步 //首先创建两个指针 这里不能让快慢指针从同一位置开始 不会进入while循环 ListNode fast = head.next; ListNode slow = head; //遍历链表 如果两者没相遇就一直遍历 没到链表的末尾就一直遍历 while(fast != null && fast.next != null && fast.next.next != null) {
//相遇 说明有环 if(fast == slow) {
return true; } slow = slow.next; fast = fast.next.next; } //退出while循环说明相遇 就有环 return false; }}

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

你可能感兴趣的文章
信安入门神级书单
查看>>
【IPFS指南】IPFS的竞争对手们(一)
查看>>
docker更换国内镜像
查看>>
CentOS 下 tree命令用法详解
查看>>
docker上传镜像至Registry时https报错解决方法
查看>>
安装 docker-compose (实测可用,妈妈再也不用担心被墙了)
查看>>
docker下删除none的images
查看>>
Linux提权获取敏感信息方法
查看>>
Ubuntu 16.04开机A start job is running for Raise network interface(5min 4s)解决方法
查看>>
Ubuntu 16.04开机隐藏菜单缩短时间
查看>>
Ubuntu 更换国内源
查看>>
Ubuntu16.04下Docker pull connection refused 解决办法
查看>>
postgres基本操作(个人总结版)
查看>>
The AnimationClip 'Walk' used by the Animation component 'Pig' must be marked as Legacy.
查看>>
《Linux内核设计与实现》- Linux的进程
查看>>
inet_ntoa()
查看>>
POSIX消息队列mq_open问题
查看>>
两个数组a[N],b[N],其中A[N]的各个元素值已知,现给b[i]赋值,b[i] = a[0]*a[1]*a[2]…*a[N-1]/a[i];
查看>>
用户态切换到内核态的3种方式
查看>>
笔试常见的智力题(附答案)
查看>>