JAVA生成带环的单向链表(针对leetcode是否有环那道题)

leetcode上面有一道题是判断单向链表是否有环,方法基本上都是用快慢指针。

但是我突然想测试一下,但是不知道怎么生成有环的链表,别说有环的,就是生成个链表都挺难的。

所以自己就在网上找了一下,发现生成链表还是有的。

但是没有生成带环的链表,所以自己总结了一下,写了一个带环的链表供大家查看。

链表的实体如下:

package com.leetcode.linklist.po;

public class ListNode {

	public int node;
	public ListNode next;
	
	public ListNode(int node, ListNode next) {
		this.node = node;
		this.next = next;
	}
}

实现部分如下:

package com.leetcode.linklist;

import org.mockito.asm.tree.IntInsnNode;

import com.leetcode.linklist.po.ListNode;

/**
 * 判断链表是否存在环
 * @author fei.meng
 *
 */
public class LinkList001 {
	
	static ListNode head;
	
	public static void main(String[] args) {
		init();
		add(getNode(6));// 这里面去第7个
		print();
	}
	
	/**
	 * 链表初始化
	 */
	public static void init() {
		for(int i=0;i<10;i++) {
			add(new ListNode(i, null));
		}
	}
	
	/**
	 * 为了生成环需要取到环节点的指针
	 * @param i
	 * @return
	 */
	public static ListNode getNode(int i) {
		int count = 0;
		ListNode temp = head;
		while(temp.next != null) {
			if(count == i) {
				//return temp;
				break;
			}
			temp = temp.next;
			count++;
		}
		return temp;
	}
	
	/**
	 * 链表的添加
	 * @param node
	 */
	public static void add(ListNode node) {
		ListNode temp = head;
		
		if(head == null) {
			head = node;
			return;
		}
		
		while(temp.next != null) {
			temp = temp.next;
		}
		temp.next = node;
	}
	
	/**
	 * 打印链表
	 * 因为有环所以只循环了20次
	 * 实际上是无限循环的
	 */
	public static void print() {
		StringBuffer buff = new StringBuffer();
		
		ListNode temp = head;
		
		buff.append(temp.node);
		
		int count = 0;
		
		while(temp.next != null) {
			buff.append("->");
			temp = temp.next;
			buff.append(temp.node);
			System.out.println(buff.toString());
			
			count++;
			
			if(count == 20) {
				break;
			}
		}
	}

	/**
	 * 判断链表是否有环
	 * @param node
	 * @return
	 */
	public static boolean isLinkedCycle(ListNode node) {
		
		if(node == null) {
			return false;
		}
		
		ListNode fast = node;
		ListNode slow = node;
		
		while(fast.next != null && fast.next.next != null) {
			slow = slow.next;
			fast = fast.next.next;
			
			if(slow == fast) {
				return true;
			}
		}
		return false;
	}
	
}

好了,以上就是实现的全部过程,有问题留言。下班~~
 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值