Skip to content

Latest commit

 

History

History
executable file
·
71 lines (36 loc) · 1.99 KB

141. Linked List Cycle.md

File metadata and controls

executable file
·
71 lines (36 loc) · 1.99 KB

#

一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github

欢迎大家关注我的新浪微博,我的新浪微博

欢迎转载,转载请注明出处

##(一)题目

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) {

        ListNode* p1 = head;//慢指针

        ListNode* p2 = head;//快指针

        while(p1!=NULL&&p2!=NULL&&p2->next!=NULL)//如果没有环,总会指向NULL

        {

            p1=p1->next;

            p2=p2->next->next;

            if(p1==p2) return true;//慢指针追上快指针,表示成环

        }

        return false;

    }

};