判断链表中是否有环
判断链表中是否有环
http://www.nowcoder.com/questionTerminal/650474f313294468a4ded3ce0f7898b9
思路:使用快慢指针,具体如下:如果链表有环,那么快慢指针将会在环中相遇;如果没有环,快指针将到达链表尾
注意点:快指针前进的步伐要比慢指针大,不然两者无法相遇。其实就是追及问题,没有速度差的话,怎么会追上呢?
代码:
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null||head.next==null) return false;
ListNode cur = head;
ListNode next = cur.next;
while(next!=null){
if(cur==next) return true;
cur = cur.next;
if(next.next==null)return false;
next = next.next.next;
}
return false;
}
}
查看3道真题和解析