链表中环的问题

来源:互联网 发布:嘉兴行知小学排名 编辑:程序博客网 时间:2024/06/16 18:14

Given a linked list, determine if it has a cycle in it.

Follow up:

Can you solve it without using extra space?

表示对递归真的是比较不会用啊,大神们如果有好的学习递归的信息,留下脚印啊!

循环实现表示超时!!!

/** * Definition for singly-linked list. * class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {       public boolean hasCycle(ListNode head){       if(head == null || head.next == null) return false;       if(head.next == head) return true;       ListNode nextNode = head.next;        head.next = head;       boolean isCycle = hasCycle(nextNode);       return isCycle;   }    // public boolean hasCycle(ListNode head) {       //  if(head==null||head.next==null){    //      return false;    //  }    //  ListNode first=head;    //  ListNode last=head.next;    //  while(last!=null){    //      first=first.next;    //      last=last.next;         //      if(first==last){    //          return true;    //      }             //  }    //  return false;         // }}


0 0
原创粉丝点击