LeetCodeOJ. Linked List Cycle

来源:互联网 发布:我的淘宝如何换帐号 编辑:程序博客网 时间:2024/06/07 18:57

试题请参见: 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;    }};
0 0
原创粉丝点击