Java语言 检测单链表是否有环

mac2022-06-30  95

 

/** * 判断链表是否有环 * @author Administrator * */public class P238 { public static void main(String[] args) { Scanner in=new Scanner(System.in); char[] c=in.nextLine().toCharArray(); in.close(); SystemIn inn=new SystemIn(); Node1 head=inn.systemIn(c); Node1 h=head; inn.systemOut(h); System.out.print(IsLoop(head)); } public static Node1 systemIn(char[] ch) { if(ch==null||ch.length==0) return null; Node1 head=new Node1('0'); Node1 temp=head; for(int i=0;i<ch.length-1;i++) { Node1 cur=new Node1(ch[i]); temp.next=cur; temp=temp.next; } return head.next; } public static boolean IsLoop(Node1 head) { Node1 low =head; Node1 fast=head; if(fast==null) return false; while(fast!=null&&fast.next!=null&&fast.next.next!=null) { low=low.next; fast=fast.next.next; if(low==fast) { return true; } } return !(fast==null||fast.next==null); }}

转载于:https://www.cnblogs.com/sgbe/p/10726227.html

最新回复(0)