1. 程式人生 > >騰訊//環形連結串列

騰訊//環形連結串列

環形連結串列

給定一個連結串列,判斷連結串列中是否有環。

進階:
你能否不使用額外空間解決此題?

(轉化為追擊相遇問題)

/**
 * 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) {
        ListNode slow = new ListNode(0);
        ListNode fast = new ListNode(0);
        if(head==null||head.next==null)
            return false;
        else{
            fast = head.next;
            slow = head;
            while(fast!=null){
                if(fast.val == slow.val)
                    return true;
                else{
                    fast = fast.next;
                    if(fast==null)
                        return false;
                    else{
                        fast = fast.next;
                        slow = slow.next;
                    }
                }
            }
        }
        return false;
    }
}
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        ListNode *fast;
        ListNode *slow;
        if(head==nullptr||head->next==nullptr){
            return false;
        }else{
            fast = head->next;
            slow = head;
            while(fast!=nullptr){
                if(fast==slow)
                    return true;
                else{
                    fast = fast->next;
                    if(fast==nullptr)
                        return false;
                    else{
                        fast = fast->next;
                        slow = slow->next;
                    }
                }
            }
            return false;
        }
    }
};