java 判断链表有环_Java判断链表是否有环的两种实现方法

package demo6;

import java.util.HashMap;

import demo6.LinkReverse2.Node;

/**

* 判断链表是否有环的方法

* @author mengfeiyang

*

*/

public class LinkLoop {

public static boolean hasLoop(Node n){

//定义两个指针tmp1,tmp2

Node tmp1 = n;

Node tmp2 = n.next;

while(tmp2!=null){

tmp1 = tmp1.next; //每次迭代时,指针1走一步,指针2走两步

tmp2 = tmp2.next.next;

if(tmp2 == null)return false;//不存在环时,退出

int d1 = tmp1.val;

int d2 = tmp2.val;

if(d1 == d2)return true;//当两个指针重逢时,说明存在环,否则不存在。

}

return true; //如果tmp2为null,说明元素只有一个,也可以说明是存在环

}

//方法2:将每次走过的节点保存到hash表中,如果节点在hash表中,则表示存在环

public static boolean hasLoop2(Node n){

Node temp1 = n;

HashMap ns = new HashMap();

while(n!=null){

if(ns.get(temp1)!=null)return true;

else ns.put(temp1, temp1);

temp1 = temp1.next;

if(temp1 == null)return false;

}

return true;

}

public static void main(String[] args) {

Node n1 = new Node(1);

Node n2 = new Node(2);

Node n3 = new Node(3);

Node n4 = new Node(4);

Node n5 = new Node(5);

n1.next = n2;

n2.next = n3;

n3.next = n4;

n4.next = n5;

n5.next = n1; //构造一个带环的链表,去除此句表示不带环

System.out.println(hasLoop(n1));

System.out.println(hasLoop2(n1));

}

}

执行结果:

true

true

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值