前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Linked List Cycle

Linked List Cycle

作者头像
用户1624346
发布2018-04-17 16:31:48
4530
发布2018-04-17 16:31:48
举报
文章被收录于专栏:calmoundcalmound

问题:判断链表是否有环。 分析:利用快慢指针slow,fast          slow指针每次走一步,fast指针每次走两步,倘若存在环,则slow和fast必定在某一时刻相遇。          由于fast指针走的比slow快所以循环的时候只需要判断fast和fast->next不为空,判断fast->next是因为防止出现fast->NULL->next这种情况

代码语言:javascript
复制
/**
 * 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 *fast,*slow;
         if(head==NULL) return false;
         slow=head;
         fast=head->next;
         while(fast!=NULL && fast->next!=NULL)
         {
             if(slow==fast) return true;
             slow=slow->next;
             fast=fast->next->next;
         }
         return false;
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2014-07-31 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档