141. Linked List Cycle

来源:互联网 发布:中国技术壁垒知乎 编辑:程序博客网 时间:2024/04/30 11:31

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

Follow up:

Can you solve it without using extra space?

快慢指针,但不额外占用空间的方法没找到。

/** * 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) {        struct ListNode* p1 = head;    struct ListNode* p2 = head;    while (p1 && p1->next)    {    p1 = p1->next->next;    p2 = p2->next;    if (p1 == p2)    return true;    }    return false;    }};


0 0
原创粉丝点击