博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Linked List Cycle --判断链表是否有环
阅读量:4108 次
发布时间:2019-05-25

本文共 714 字,大约阅读时间需要 2 分钟。

问题:

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

转载地址:http://hktsi.baihongyu.com/

你可能感兴趣的文章
web.py 0.3 新手指南 - 使用db.query进行高级数据库查询
查看>>
web.py 0.3 新手指南 - 多数据库使用
查看>>
一步步开发 Spring MVC 应用
查看>>
python: extend (扩展) 与 append (追加) 的差别
查看>>
「译」在 python 中,如果 x 是 list,为什么 x += "ha" 可以运行,而 x = x + "ha" 却抛出异常呢?...
查看>>
谷歌阅读器将于2013年7月1日停止服务,博客订阅转移到邮箱
查看>>
浅谈JavaScript的语言特性
查看>>
Hid Report Descriptor
查看>>
strlen,strcpy,strcat,strcmp,strstr各代表什么意思
查看>>
手机GPRS、短信等设置
查看>>
结构体声明
查看>>
SIM300 AT指令集
查看>>
lwIP移植工作
查看>>
USB 协议简介
查看>>
USB入门系列之一----基础知识
查看>>
USB入门系列之二-----USB的连接模型
查看>>
USB入门系列之三-----USB的电气特性
查看>>
USB入门系列之四 —— USB的线缆以及插头、插座【转】
查看>>
USB入门系列之五 —— USB设备的插入检测机制
查看>>
USB入门系列之六 —— USB设备的枚举过程
查看>>