141. Linked List Cycle(Linked List-Easy)

来源:互联网 发布:淘宝店铺访客特点 编辑:程序博客网 时间:2024/06/06 04:02

    Description:Given a linked list, determine if it has a cycle in it.
    Follow up:
    Can you solve it without using extra space?

C代码:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */bool hasCycle(struct ListNode *head) {    struct ListNode *fast = (struct ListNode *)malloc(sizeof(struct ListNode));    struct ListNode *slow = (struct ListNode *)malloc(sizeof(struct ListNode));    fast = head;    slow = head;    while(fast != NULL && fast->next != NULL){        slow = slow->next;        fast = fast->next->next;        if(fast == slow){            return true;        }    }    return false;}

C++代码::

/** * 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 = head;        ListNode *slow = head;        while(fast != NULL && fast->next != NULL){            slow = slow->next;            fast = fast->next->next;            if(fast == slow){                return true;            }        }        return false;    }};
0 0
原创粉丝点击