循环链表判断(Java实现)

方法一:通过快慢指针的方式来解决 
//本方法未经测试,如有问题请多包容

boolean isLoopListTable(ListNode head){
    ListNode headFirst=head;
    ListNode headLenT=head;
    ListNode headLenO=head;
    boolean res=false;
    while(1){
        if(headLenT==null||headLenT.next==null){
            break;
        }
        if(headLenT==headLenO||headLenT.next==headLenO){
            res=true;
            break;
        }
        headLenT=headLenT.next.next;
        headLenO=headLenO.next;
    }
    return res;
}
  • 方法二:通过借助辅助空间,将所有地址空间都存在辅助空间中,然后不断的遍历链表,通过hash表的方式查看是否地址是否已经,如果已经存在,则链表存在是循环链表,如果已经遍历到了最后发现链表为空,则说明链表不为循环链表

猜你喜欢

转载自blog.csdn.net/liuchaoxuan/article/details/80561434