Leetcode Linked List Cycle

来源:互联网 发布:大理旅游 知乎 编辑:程序博客网 时间:2024/05/10 03:07

判断一个链表是不是循环链表。

初始化两个指向头部的指针,一个每次走两步,一个每次走一步,如果相遇就是循环链表,反之则不是。

特殊情况是空链表不是循环链表。

/** * 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) {        // IMPORTANT: Please reset any member data you declared, as        // the same Solution instance will be reused for each test case.        if(head == NULL || head->next == NULL)    return false;        ListNode *one = head, *two = head;        while(one != NULL){            if(two->next == NULL){                two = head->next;            }            else if(two->next->next == NULL){                two = head;            }            else two = two->next->next;            one = one->next;            if(one == two)                return true;        }        return false;    }};

原创粉丝点击