题解 | #NC4 判断链表中是否有环#

判断链表中是否有环

http://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9

'''
/**

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

      set<ListNode*>s;
      while(head){
          if(s.find(head)!=s.end()){
              return true;
          }
          s.insert(head);
          head=head->next;
      }
      return false;

    }
    };
    '''
    '''
    /**

  • 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,*fast=head,*meet=nullptr;
      while(fast){
          slow=slow->next;
          fast=fast->next;
          if(!fast)
              return false;
          fast=fast->next;
          if(fast==slow){
              return true;
          }
      }
     // if(meet==nullptr) return false;

    // while(head&&meet){
    // if(head==meet){
    // return true;
    // }
    // head=head->next;
    // meet=meet->next;
    // }

      return false;

    }
    };
    '''

全部评论

相关推荐

吴offer选手:HR:我KPI到手了就行,合不合适关我什么事
点赞 评论 收藏
分享
Southyeung:我说一下我的看法(有冒犯实属抱歉):(1)简历不太美观,给我一种看都不想看的感觉,感觉字体还是排版问题;(2)numpy就一个基础包,机器学习算法是什么鬼?我感觉你把svm那些写上去都要好一点。(2)课程不要写,没人看,换成获奖经历;(3)项目太少了,至少2-3个,是在不行把网上学习的也写上去。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务