zoukankan      html  css  js  c++  java
  • Leetcode: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?

    方案一:

     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==NULL) return false;
    13         ListNode* Node = NULL;
    14         ListNode* temp = NULL;
    15         Node = head;
    16         while(head->next!=NULL)
    17         {
    18             temp = head;
    19             head = head->next;
    20             temp->next = Node;
    21             if(head->next==Node)
    22                 return true;
    23         }
    24         return false;
    25     }
    26 };

    方案二:

     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         // head ==null?
    13         if(head==NULL) return false;
    14         ListNode *fast = head->next, *slow=head;
    15         while(fast!=NULL && fast->next!=NULL)
    16         {
    17             if(fast==slow)
    18                 return true;
    19             fast = fast->next->next;
    20             slow = slow->next;
    21         }
    22         return false;
    23     }
    24 };

    建议与易出错地方:

    1.在纸上写代码时,开始留些空白,如果需要处理边界情况,可直接加上。

    2. 声明指针变量时一定要保持*在变量上的好习惯,否则容易写成 ListNode* fast=head, slow = head; 这就错了!

    3. 过程中一个错是  开始初始化直接

     ListNode *fast = head, *slow=head;
    后面fast==slow的判断,就直接为真了。
  • 相关阅读:
    编辑器 --- Visual Studio Code 英文界面转换成中文(简体)
    CSS3 -- column 实现瀑布流布局
    CSS3 -- 边框圆角
    CSS3 -- 弹性盒
    自适应布局要素
    Vue -- 基础知识
    Vue -- element-ui el-table 的合计在第一行显示并可点击
    如何在网页标题栏title加入logo(icon)图标?
    linux下暴力破解工具hydra【转】
    linux 服务简介
  • 原文地址:https://www.cnblogs.com/soyscut/p/3691521.html
Copyright © 2011-2022 走看看