zoukankan      html  css  js  c++  java
  • leetcode-142. Linked List Cycle II

    Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

    Note: Do not modify the linked list.

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

    思路:不同于141. Linked List Cycle 这题的head节点可能没在环里,而且不光判断是否有环,还要返回环的起点,所以不能再用快慢指针了,改用修改节点数据值,修改为一个不常用的数,我修改为INT_MAX。如果遇到值为INT_MAX的节点,就说明有环,并且为环的起点(虽然这种方法在逻辑上不完美,但是这题Accepted了,如果有更好的方法,欢迎指教)

    Accepted Code:

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode *detectCycle(ListNode *head) {
    12         if(head==nullptr)
    13         return nullptr;
    14         
    15         ListNode* flag=nullptr;
    16         while(head)
    17         {
    18             head->val=INT_MAX;
    19             head=head->next;
    20             if(head==nullptr)
    21             return nullptr;
    22             if(head->val==INT_MAX)
    23             {
    24                 flag=head;
    25                 break;
    26             }
    27         }
    28         return flag;
    29     }
    30 };
  • 相关阅读:
    剑指 Offer 13. 机器人的运动范围
    32个触发事件XSS语句的总结
    CSS实现垂直居中的5种方法
    微信、QQ浏览器X5内核问题汇总
    值得关注的顶级开发者社区
    HTML5本地数据库(WebSQL)[转]
    按首字母排序汉字
    jQuery 源码中的 camelCase
    jQuery中的quickExpr
    手绘计划
  • 原文地址:https://www.cnblogs.com/hongyang/p/6438580.html
Copyright © 2011-2022 走看看