LeetCodeOJ. Linked List Cycle

試題請參見: https://oj.leetcode.com/problems/linked-list-cycle/

題目概述

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

Follow up:
Can you solve it without using extra space?

解題思路

數據結構典型例題: 使用快慢指針.
快指針遍歷時, 一次遍歷2個元素; 慢指針一次遍歷1個元素.
若他倆不相等, 則不存在環.

遇到的問題

RunTime Error

遍歷時, 請檢查 fastNode->next 是否爲NULL, 否則會出現Runtime Error.

源代碼

/**
 * 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* fastNode = head;
        ListNode* slowNode = head;

        while ( fastNode != NULL && slowNode != NULL ) {
            if ( fastNode->next != NULL ) {
                fastNode = fastNode->next->next;
            } else {
                return false;
            }
            slowNode = slowNode->next;

            if ( fastNode == slowNode ) {
                return true;
            }
        }
        return false;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章