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<Node,Node> ns = new HashMap<Node,Node>();
		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
相關文章
相關標籤/搜索