141. Linked List Cycle (Easy)

来源:互联网 发布:安卓魔音软件 编辑:程序博客网 时间:2024/05/29 19:13

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

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

Solution:

C:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */bool hasCycle(struct ListNode *head) {    if(head == NULL || head->next == NULL) {        return false;    }    if(head->next == head) {        return true;    }    struct ListNode* low = head;    struct ListNode* fast = head;    while(low && fast) {        low = low->next; // low指针一次走一步        fast = fast->next;        if(fast != NULL) {            fast = fast->next; // fast指针一次走两步        }        if(low == fast) {  //两个指针相遇表示存在环            return true;        }    }    return false;}

最开始犯了个低级错误,把while循环里的if(low == fast)判断写到while循环的最前面了,所以提交一直不通过,因为low和fast最开始就是相等的,都指向head,应该在low和fast开始走之后再判断是否相等。

0 0
原创粉丝点击