快慢指针解决单向链表是否有环的一系列问题

talk is cheap,show me the code......

证明参考:https://www.cnblogs.com/zhuzhenwei918/p/7491892.html

package singleLinkedList;

/** 
* @author Leon
* @date 创建时间:2017年10月15日 下午6:13:40
* @version 1.0
* 类说明 :
* 单向链表相关问题   例如:1 - 2 - 3 - 4 - 5 - 6 - 4 - .....
* 1、是否有环
* 2、环的长度
* 3、带环链表的实际长度
*/
public class Test
{
	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);
		Node n6 = new Node(6);

		n1.next = n2;
		n2.next = n3;
		n3.next = n4;
		n4.next = n5;
		n5.next = n6;
		n6.next = n4;

		System.out.println(isHoop(n1));
		System.out.println(getLengthOfHoop(n1));
		System.out.println(getLengthOfList(n1));
	}

	/*
	 * 对于问题1,使用追赶的方法,设定两个指针slow、fast,从头指针开始,每次分别前进1步、2步。
	 * 如存在环,则两者相遇;如不存在环,fast遇到NULL退出
	 */
	private static String isHoop(Node n1)
	{
		Node slow, fast;
		slow = n1;
		fast = n1;
		while (fast != null)
		{
			fast = fast.next.next;
			slow = slow.next;
			if (fast == slow)
			{
				return "链表有环哦~";
			}
		}

		return "链表没环哦~";
	}

	/*
	 * 对于问题2,记录下问题1的碰撞点p,slow、fast从该点开始,再次碰撞所走过的操作数就是环的长度s。
	 */
	private static String getLengthOfHoop(Node n1)
	{
		Node slow, fast, p = null;
		slow = n1;
		fast = n1;
		while (fast != null)
		{
			fast = fast.next.next;
			slow = slow.next;
			if (fast == slow)
			{
				p = fast;
				//System.out.println(p.value);
				break;
			}
		}
		if (p == null)
		{
			
			return "链表没环";
		}

		slow = p.next;
		fast = p.next.next;
		int operation = 1;
		while (slow.value != fast.value)
		{
			slow = slow.next;
			fast = fast.next.next;
			operation++;
		}
		return "环的长度是:"+String.valueOf(operation);
	}
	
	/*
	 * 对于问题3,和前半部分加在一起就可以了。
	 */
	private static String getLengthOfList(Node n1)
	{
		Node slow, fast, p = null;
		slow = n1;
		fast = n1;
		while (fast != null)
		{
			fast = fast.next.next;
			slow = slow.next;
			if (fast == slow)
			{
				p = fast;
				//System.out.println(p.value);
				break;
			}
		}
		if (p == null)
		{
			return "链表没环";
		}
		
		slow=n1;
		int result=0;
		while(slow.value!=p.value)
		{
			result++;
			slow=slow.next;
			//System.out.println("hello");
		}
		//System.out.println(result);
		//System.out.println(getLengthOfHoop(n1).charAt(getLengthOfHoop(n1).length()-1));
		int resultT = result+Character.getNumericValue(getLengthOfHoop(n1).charAt(getLengthOfHoop(n1).length()-1));
		//System.out.println(resultT);
		return "链表长度:"+resultT;
	}
}

class Node
{
	public int value;
	public Node next = null;

	public Node(int value)
	{
		super();
		this.value = value;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值