每日算法(六)--java判断单链表是否有环

每日算法(六)–java判断单链表是否有环

可以设计两个快慢指针,一个每次走两步一个每次走一步,如果快慢指针碰面,则说明有环

1.创建链表

public class ListNode {
	private int data;   //这个节点的数据
	ListNode next;  //指向下个结点
	
	
	public ListNode(int data) {
		super();
		this.data = data;
	}`在这里插入代码片`

2.数组转化成链表

public  static ListNode arrayToList(int arr[]){
		ListNode root=new ListNode(arr[0]);//将数组第一个元素存放根节点
		ListNode other=root;  //临时变量other存放根节点
		for(int i=1;i<arr.length-1;i++){  //根节点已经赋值,所以从1开始
			ListNode temp=new ListNode(arr[i]); //依次放入一个新生成的节点里
			other.next=temp;    //  将other下个节点指向新节点
			other =temp;  //将other指向下个节点
			
		}
		ListNode last=new ListNode(arr[arr.length-1]);
	   last.next=root;
		return root;
	}

3.判断是否有环

public  static ListNode hasCircle(ListNode head){
		
		ListNode slow,fast;//快慢指针
		slow=fast=head;    //都从头部开始
		while(fast!=null&&fast.next!=null){
			slow=slow.next;   //慢指针每次一步
			fast=fast.next.next;  //快指针每次两步
			//有环,输出环的长度
			while(fast==slow){
				System.out.println("有环");
		
				int length=1;
		       slow=slow.next;
			    fast=fast.next.next;
				 while(fast!=slow){
					 length++;
					 slow=slow.next;
					 fast=fast.next.next;
				 }
				 System.out.println("环的长度为"+length);
                               return slow;
			}
		}
		//没环
		System.out.println("没环");
		return null;
	}

猜你喜欢

转载自blog.csdn.net/Tong_Nan/article/details/89488861