Linked List Cycle

原创 2016年05月30日 16:20:37
Given a linked list, determine if it has a cycle in it.

Follow up:

Can you solve it without using extra space?

题目:如何判断一个链表是否是含有环的

思路:使用两个指针,遍历整个链表,一个走一步,一个走两步。直到两个指针相等且都不为NULL的话则说明这个链表有环

/**
 * 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) {
        if(head==NULL)
            return false;
        ListNode *p=head,*q=p->next;
        bool res = false;
        while(p&&q&&p!=q)
        {
            p=p->next;
            int times=2;
            while(q&×>0)
            {
                times--;
                q=q->next;
            }
        }
        if(p==q)
            res=true;
        return res;
    }
    
};

如下代码比较简洁

/**
 * 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 *slow=head;
        ListNode *fast=head;
        while(true)
        {
            if(fast==NULL||fast->next==NULL)
                return false;
            slow=slow->next;
            fast=fast->next->next;
            if(slow==fast)
                break;
        }
        return true;
    }
};



版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode Linked List Cycle II(找到带环单向链表的环起始位置)

题目要求: Given a linked list, return the node where the cycle begins. If there is no cycle, return...
  • lqcsp
  • lqcsp
  • 2014年04月06日 11:52
  • 600

链表环查找(Linked List Cycle II)

问题: Given a linked list, return the node where the cycle begins. If there is no cycle, return nu...

数据结构与算法[LeetCode]—Linked List Cycle 确定单链表是否有环,并找出第一个环结点

Linked List Cycle Given a linked list, determine if it has a cycle in it. Follow up: Can you s...

leetcode Linked List Cycle II 单链表中的环问题集锦

Linked List Cycle Given a linked list, determine if it has a cycle in it. Follow up: Can you s...

LeetCode OJ:Linked List Cycle II

Linked List Cycle II  Total Accepted: 4952 Total Submissions: 16449My Submissions Given ...

【LeetCode】Linked List Cycle II

参考链接 http://www.cnblogs.com/x1957/p/3406448.html 题目描述 Linked List Cycle II   Give...

Linked List Cycle I&&II

Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without usin...

leetcode:Linked List Cycle II

COPY FROM: 比I麻烦点的就是找到循环开始点TAT I只是判断是否循环。要求不使用额外空间(不然hash就可以了 按I的思路,我们又慢指针S和快指针F。。。F走两...

[LeedCode]Find the Duplicate Number/Linked List Cycle II

看到别人一个时间复杂度为O(n)的解法,觉得很有意思。记录一下。题目: Given an array nums containing n + 1 integers where each intege...

【LeetCode】Linked List Cycle II

题目 Given a linked list, return the node where the cycle begins. If there is no cycle, return nu...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Linked List Cycle
举报原因:
原因补充:

(最多只允许输入30个字)