前言
循环链表的特点是没有结束指针,通过遍历链表判断链表中是否存在重复元素,这里需要使用HashSet或HashSet的数据结构。
实现原理
1.一个HashSet的结构体
2.遍历变量链表直至链表末尾。
3.遍历到链表的值与HashSet中值进行比对,如果出现一致则返回true。如果变量至链表尾部,未发现元素与HashSet中的一致,则返回fasle。
具体代码实现
package test4;
import java.util.HashSet;
class ListNode{
int val;
ListNode next;
public ListNode(int val){
this.val =val;
this.next=null;
}
}
public class Solution {
HashSet<ListNode> hashset=new HashSet();
public boolean hasCycle(ListNode head) {
boolean flag=false;
while(head!=null){
if(!hashset.contains(head)){
hashset.add(head);
}else{
flag=true;
break;
}
head=head.next;
}
return flag;
}
public static void main(String[] args) {
Solution solution=new Solution();
ListNode headA=new ListNode(1);
ListNode currentA=headA;
ListNode temp=null;
for(int i=2;i<5;i++){
ListNode newListNode=new ListNode(i);
currentA.next=newListNode;
currentA=currentA.next;
if(i==3){
temp=newListNode;
}
}
currentA.next=temp;
System.out.println(solution.hasCycle(headA));
}
}
QA:待定