zoukankan      html  css  js  c++  java
  • LeetCode 141. Linked List Cycle

    Given a linked list, determine if it has a cycle in it.

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

     

    题目要求判断链表是否有环形,题目不难,方法很巧,典型的双指针问题,一开始现实判断最简单的空链表或者只有一个节点但是无环的情况,接下来设置一快一慢两个指针,快指针每次比慢指针夺走一步,倘若无环,快指针一定会先到达null指针位置;如果有环,那么最后快指针一定会追上慢指针

    代码如下:

     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     bool hasCycle(ListNode *head) {
    12         if (!head || !head->next)
    13            return false;
    14         ListNode *slow = head;
    15         ListNode *fast = head->next;
    16         while (slow != fast)
    17         {
    18             if (fast->next == nullptr || fast->next->next == nullptr)
    19                 return false;
    20             slow = slow->next;
    21             fast = fast->next->next;
    22         }
    23         return true;
    24     }
    25 };

     

  • 相关阅读:
    初学git(一):创建本地“仓库”
    git常用命令
    Linux学习(一):从图形界面进入命令行及命令行进入图形界面
    继承与派生
    数据类型和表达式
    UDP
    网络与通信
    枚举类型
    结构体
    第一个随笔
  • 原文地址:https://www.cnblogs.com/dapeng-bupt/p/8261761.html
Copyright © 2011-2022 走看看