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的判断,就直接为真了。
  • 相关阅读:
    Microsoft office 2013安装图解
    6.2单一继承
    #include <QLabel>
    #include <QDebug>
    9.1运算符重载
    简单QT界面信号图形化输入输出
    类指针引用
    NULL和nullptr的区别
    网易云课堂_C语言程序设计进阶_第8周:图形交互程序
    5.3友元函数
  • 原文地址:https://www.cnblogs.com/soyscut/p/3691521.html
Copyright © 2011-2022 走看看