您的位置:首页 > 编程语言 > Java开发

(整理)Java实现链表-----判断链表是否有环

2016-03-23 14:30 519 查看
import java.util.*;
class Node{
Node next = null;
int data;
public Node(int data){
this.data = data;
}
}
public class MyLinkedList {
Node head = null;
public void addNode(int d){
Node newNode = new Node(d);
if(head == null){
head = newNode;
return;
}
Node tmp = head;
while(tmp.next != null){
tmp = tmp.next;
}
tmp.next = newNode;
}
public Boolean deleteNode(int index){
if(index<1||index>length()){
return false;
}
if(index == 1){
head = head.next;
return true;
}
int i = 2;
Node preNode = head;
Node curNode = preNode.next;
while(curNode != null){
if(i == index){
preNode.next = curNode.next;
return true;
}
preNode = curNode;
curNode = curNode.next;
i++;
}
return true;
}
public int length(){
int length = 0;
Node tmp = head;
while(tmp != null){
length++;
tmp = tmp.next;
}
return length;
}
public void printList(){
Node tmp = head;
int i=0;
while(tmp != null&&i<20){
i++;
System.out.println(tmp.data);
tmp = tmp.next;
}
}
public Node findNode(int index){
int i;
Node p = this.head;
for(i = 1; i<index; i++){
p = p.next;
}
return p;
}
public boolean IsLoop(){//关键函数
Node fast = head;//快指针
Node slow = head;//慢指针
if(fast == null){
return false;
}
while(fast.next != null){//快指针是慢指针的二倍
fast = fast.next.next;
slow = slow.next;
if(fast == slow){//快慢相遇则有环,且此处为环的入口
return true;
}
}
return false;
}
public void ReverseIteratively(){
Node head = this.head;
Node pReversedHead = head;
Node pNode = head;
Node pPre = null;

while(pNode != null){
Node pNext = pNode.next;
if(pNext == null){
pReversedHead = pNode;
}
pNode.next = pPre;
pPre = pNode;
pNode = pNext;
}
this.head = pReversedHead;
}
public static void main(String[] args){
MyLinkedList list = new MyLinkedList();
list.addNode(7);
list.addNode(6);
list.addNode(5);
list.addNode(4);
list.addNode(3);
list.addNode(2);
list.addNode(1);
Node p = list.findNode(4);
Node p1 = list.findNode(7);
// p1.next = p;
list.printList();
boolean isloop = list.IsLoop();
System.out.println("isloop="+isloop);

}
}


测试结果:

7

6

5

4

3

2

1

isloop=false

去掉//  后测试结果:(有环会无限输出,这里仅输出前20个)

7

6

5

4

3

2

1

4

3

2

1

4

3

2

1

4

3

2

1

4

isloop=true
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链表 数据结构 java