C++:判断链表是否有环

判断给定的链表中是否有环。如果有环则返回true,否则返回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) {

        if(head == NULL)
        {
            return false;
        }

        ListNode *head_one_step = head;
        ListNode *head_two_step = head;

        while((head_one_step != NULL) && (head_two_step != NULL))
        {
            head_one_step = head_one_step->next;
            if(head_two_step->next == NULL)
            {
                return false;
            }
            else
            {
                head_two_step = head_two_step->next->next;
            }
            
            if(head_one_step == head_two_step)
            {
                return true;
            }
        }
        
        return false;
    }
};

总结:

不知道为什么让快指针先走一步的话,会出错。后面调查一下。

        ListNode *head_one_step = head;
        ListNode *head_two_step = head->next;

猜你喜欢

转载自blog.csdn.net/xikangsoon/article/details/110590199