15算法课程 141. Linked List Cycle

来源:互联网 发布:天天直播网络电视下载 编辑:程序博客网 时间:2024/04/29 13:40


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

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


solution:

快慢指针解题


code:

class Solution {public:    bool hasCycle(ListNode *head) {        if(!head) return false;        ListNode *p1 = head, *p2 = head->next;        while(p1 && p2){            if(p1 == p2)                return true;            p1 = p1->next;            p2 = p2->next;            if(p2)                p2 = p2->next;        }        return false;    }};


原创粉丝点击