zoukankan      html  css  js  c++  java
  • LeetCode141: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,所以一定会相遇,而不会出现快指针直接跳过慢指针的情况。

    实现代码:

    #include <iostream>
    using namespace std;
    
    /**
    Linked List Cycle
     */
     
    struct ListNode {
         int val;
         ListNode *next;
         ListNode(int x) : val(x), next(NULL) {}
    };
    void addNode(ListNode* &head, int val)
    {
        ListNode *node = new ListNode(val);
        if(head == NULL)
        {
            head = node;
        }
        else
        {
            node->next = head;
            head = node;
        }
    }
    void printList(ListNode *head)
    {
        while(head)
        {
            cout<<head->val<<" ";
            head = head->next;
        }
    }
    
    class Solution {
    public:
        bool hasCycle(ListNode *head) {
            if(head == NULL || head->next == NULL)
                return NULL;
            ListNode *quick = head;
            ListNode *slow = head;
            while(quick && quick->next)//利用快慢指针判断有无环 
            {
                quick = quick->next->next;
                slow = slow->next;
                if(quick == slow)
                    return true;
            }
            return NULL;
                  
        }
    };
    int main(void)
    {
        ListNode *head = new ListNode(1);
        ListNode *node1 = new ListNode(2);
        ListNode *node2 = new ListNode(3);
        ListNode *node3 = new ListNode(4);
        head->next = node1;
        node1->next = node2;
        node2->next = node3;
        node3->next = node1;
        
        Solution solution;
        bool ret = solution.hasCycle(head);
        if(ret)
            cout<<"has cycle"<<endl;
        
        return 0;
    }
  • 相关阅读:
    读懂Netty的高性能架构之道
    大型网站架构演变和知识体系(转载)
    SAX,功能强大的 API
    防雪崩利器:熔断器 Hystrix 的原理与使用
    分布式系统设计系列 -- 基本原理及高可用策略
    分布式系统的事务处理
    分布式服务框架之服务化最佳实践
    深入理解 Java 虚拟机:JVM 高级特性与最佳实践
    内存屏障
    IntelliJ IDEA 2016 破解旗舰版
  • 原文地址:https://www.cnblogs.com/mickole/p/3671475.html
Copyright © 2011-2022 走看看