手机
当前位置:查字典教程网 >编程开发 >Java >java实现单链表中是否有环的方法详解
java实现单链表中是否有环的方法详解
摘要:这是一道微软经典笔试题,就是两个指针h1,h2都从头开始遍历单链表,h1每次向前走1步,h2每次向前走2步,如果h2碰到了NULL,说明环不...

这是一道微软经典笔试题,就是两个指针h1,h2都从头开始遍历单链表,h1每次向前走1步,h2每次向前走2步,如果h2碰到了NULL,说明环不存在;如果h2碰到本应在身后的h1说明环存在(也就是发生了套圈)。

如果环不存在,一定是h2先碰到NULL:

如果环存在,h2与h1一定会相遇,而且相遇的点在环内:h2比h1遍历的速度快,一定不会在开始的那段非环的链表部分相遇,所以当h1,h2都进入环后,h2每次移动都会使h2与h1之间在前进方向上的差距缩小1,最后,会使得h1和h2差距减少为0,也即相遇

复制代码 代码如下:

package org.myorg;

public class Test{

public static boolean isExsitLoop(SingleList a) {

Node<T> slow = a.head;

Node<T> fast = a.head; while (fast != null && fast.next != null) {

slow = slow.next;

fast = fast.next.next;

if (slow == fast)

return true;

}

return false;

}

public static void main(String args[]){

SingleList list = new SingleList();

for(int i=0;i<100;i++){

list.add(i);

}

System.out.print(SingleList.isExistingLoop(list));

}

}

复制代码 代码如下:

package org.myorg;

public class Node{

public Object data; //节点存储的数据对象

public Node next; //指向下一个节点的引用

public Node(Object value){

this.data = value;

}

public Node(){

this.data = null;

this.next = null;

}

}

复制代码 代码如下:

package org.myorg;

public class SingleList{

private int size;

private Node head;

private void init(){

this.size = 0;

this.head = new Node();

}

public SingleList(){

init();

}

public boolean contains(Object value){

boolean flag = false;

Node p = head.next;

while(p!=null){

if(value.equals(p.data)){

flag = true;

break;

}else(

p = p.next;

)

}

return flag;

}

public boolean add(Object value){

if(contains(value))

return false;

else{

Node p = new Node(value);

p.next=head.next;

head.next = p;

size++;

}

return true;

}

}

【java实现单链表中是否有环的方法详解】相关文章:

java中使用sax解析xml的解决方法

java this super使用方法详解

java执行bat命令碰到的阻塞问题的解决方法

java中常用的排序方法

java向多线程中传递参数的三种方法详细介绍

Java 替换字符串中的回车换行符的方法

MySQL实现远程登录的方法

JAVA实现单例模式的四种方法和一些特点

java中的枚举类型详细介绍

java中File类的使用方法

精品推荐
分类导航