一:
题目:
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)
return false;
ListNode p = head;
ListNode q = head;
while(p!=null && q!=null && p.next!=null){
p=p.next.next; //快指针
q = q.next;//慢指针
if(p==q)
return true;
}
return false;
}
}