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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值