leetcode 141. Linked List Cycle 链表循环的判定 + 双指针

来源:互联网 发布:linux下c 多线程 编辑:程序博客网 时间:2024/05/16 19:34

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

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

本题就是判断链表是否存在循环,这个方法很棒,说实话我自己是想不到的。

代码如下:

/*class ListNode {     int val;     ListNode next;     ListNode(int x) {         val = x;         next = null; }}*//*  * 题目要求是判断链表是否有环,leetcode上链表的题都是没有头结点的,这点大家要记住。 * 而且若链表有环,也是最后一个节点形成的环。 * 大家考虑这样一个问题,链表的环相当于一个圆形操场。假设有两个人在圆形操场上无限循环的跑, * 那么速度快的一定能追得上速度慢的。同理,若要判断一个链表是否有环,可设计快慢指针, * 当快慢指针都进入环的时候,若最终两个指针相遇,必可说明链表存在环。下面就要考虑快慢指针的步长, * 从跑操场的情况来看,不管慢的有多慢,快得有多快,最终肯定能相遇。同理,链表中, * 也可随意指定快慢指针的步长,无非就是跑的圈数多少的问题。  * */public class Solution {    public boolean hasCycle(ListNode head)     {        if(head==null || head.next==null)            return false;        ListNode fast=head,slow=head;        while(fast!=null && slow!=null && fast.next!=null)        {            slow=slow.next;            fast=fast.next.next;            if(fast==slow)                return true;        }        return false;    }}

下面是C++的做法,就是使用双指针来判断循环的存在与否

代码如下:

#include <iostream>#include <vector>#include <algorithm>#include <string>#include <map>#include <set>#include <climits>using namespace std;/*struct ListNode {     int val;     ListNode *next;     ListNode(int x) : val(x), next(NULL) {}};*/class Solution{public:    bool hasCycle(ListNode *head)     {        if (head == NULL || head->next == NULL)            return false;        ListNode* fast = head;        ListNode* slow = head;        while (fast != NULL && slow != NULL && fast->next != NULL)        {            slow = slow->next;            fast = fast->next->next;            if (fast == slow)                return true;        }        return false;    }};